博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Golang学习笔记:语言规范二
阅读量:4029 次
发布时间:2019-05-24

本文共 6674 字,大约阅读时间需要 22 分钟。

类型转换

形式为 T(x), T是一种类型,x是目标类型表达式。示例

*Point(p)        // same as *(Point(p))(*Point)(p)      // p is converted to *Point<-chan int(c)    // same as <-(chan int(c))(<-chan int)(c)  // c is converted to <-chan intfunc()(x)        // function signature func() x(func())(x)      // x is converted to func()(func() int)(x)  // x is converted to func() intfunc() int(x)    // x is converted to func() int (unambiguous)

常量转换

uint(iota)               // iota value of type uintfloat32(2.718281828)     // 2.718281828 of type float32complex128(1)            // 1.0 + 0.0i of type complex128float32(0.49999999)      // 0.5 of type float32string('x')              // "x" of type stringstring(0x266c)           // "♬" of type stringMyString("foo" + "bar")  // "foobar" of type MyStringstring([]byte{
'a'}) // not a constant: []byte{
'a'} is not a constant(*int)(nil) // not a constant: nil is not a constant, *int is not a boolean, numeric, or string typeint(1.2) // illegal: 1.2 cannot be represented as an intstring(65.0) // illegal: 65.0 is not an integer constant

字符串转换

转换一个无符号或有符号的整数位字符串时,其结果为一个utf-8形式的字符串。

string('a')       // "a"string(-1)        // "\ufffd" == "\xef\xbf\xbd"string(0xf8)      // "\u00f8" == "ø" == "\xc3\xb8"type MyString stringMyString(0x65e5)  // "\u65e5" == "日" == "\xe6\x97\xa5"

转换byte类型的slice为字符串

string([]byte{
'h', 'e', 'l', 'l', '\xc3', '\xb8'}) // "hellø"string([]byte{}) // ""string([]byte(nil)) // ""type MyBytes []bytestring(MyBytes{
'h', 'e', 'l', 'l', '\xc3', '\xb8'}) // "hellø"

转换rune类型的slice为字符串

string([]rune{0x767d, 0x9d6c, 0x7fd4})   // "\u767d\u9d6c\u7fd4" == "白鵬翔"string([]rune{})                         // ""string([]rune(nil))                      // ""type MyRunes []runestring(MyRunes{0x767d, 0x9d6c, 0x7fd4})  // "\u767d\u9d6c\u7fd4" == "白鵬翔"
[]byte("hellø")   // []byte{
'h', 'e', 'l', 'l', '\xc3', '\xb8'}[]byte("") // []byte{}MyBytes("hellø") // []byte{
'h', 'e', 'l', 'l', '\xc3', '\xb8'}
[]rune(MyString("白鵬翔"))  // []rune{0x767d, 0x9d6c, 0x7fd4}[]rune("")                 // []rune{}MyRunes("白鵬翔")           // []rune{0x767d, 0x9d6c, 0x7fd4}

常量表达式

常量表达式在编译时可只包含常量操作数和值

const a = 2 + 3.0          // a == 5.0   (untyped floating-point constant)const b = 15 / 4           // b == 3     (untyped integer constant)const c = 15 / 4.0         // c == 3.75  (untyped floating-point constant)const Θ float64 = 3/2      // Θ == 1.0   (type float64, 3/2 is integer division)const Π float64 = 3/2.     // Π == 1.5   (type float64, 3/2. is float division)const d = 1 << 3.0         // d == 8     (untyped integer constant)const e = 1.0 << 3         // e == 8     (untyped integer constant)const f = int32(1) << 33   // illegal    (constant 8589934592 overflows int32)const g = float64(2) >> 1  // illegal    (float64(2) is a typed floating-point constant)const h = "foo" > "bar"    // h == true  (untyped boolean constant)const j = true             // j == true  (untyped boolean constant)const k = 'w' + 1          // k == 'x'   (untyped rune constant)const l = "hi"             // l == "hi"  (untyped string constant)const m = string(k)        // m == "x"   (type string)const Σ = 1 - 0.707i       //            (untyped complex constant)const Δ = Σ + 2.0e-4       //            (untyped complex constant)const Φ = iota*1i - 1/1i   //            (untyped complex constant)

语句

标签

Error: log.Panic("error encountered")

发送语句

ch <- 3  // send value 3 to channel ch

自增自减语句

IncDec statement    Assignmentx++                 x += 1x--                 x -= 1

If 语句

if x > max {    x = max}if x := f(); x < y {    return x} else if x > z {    return z} else {    return y}

Switch 语句

表达式switch,用fallthrough 表示继续执行下一个case

switch tag {default: s3()case 0, 1, 2, 3: s1()case 4, 5, 6, 7: s2()}switch x := f(); {  // missing switch expression means "true"case x < 0: return -xdefault: return x}switch {case x < y: f1()case x < z: f2()case x == 4: f3()}

类型switch

switch i := x.(type) {case nil:    printString("x is nil")                // type of i is type of x (interface{})case int:    printInt(i)                            // type of i is intcase float64:    printFloat64(i)                        // type of i is float64case func(int) float64:    printFunction(i)                       // type of i is func(int) float64case bool, string:    printString("type is bool or string")  // type of i is type of x (interface{})default:    printString("don't know the type")     // type of i is type of x (interface{})}

For 语句

for a < b {    a *= 2}for i := 0; i < 10; i++ {    f(i)}var testdata *struct {    a *[7]int}for i, _ := range testdata.a {    // testdata.a is never evaluated; len(testdata.a) is constant    // i ranges from 0 to 6    f(i)}var a [10]stringfor i, s := range a {    // type of i is int    // type of s is string    // s == a[i]    g(i, s)}var key stringvar val interface {}  // value type of m is assignable to valm := map[string]int{
"mon":0, "tue":1, "wed":2, "thu":3, "fri":4, "sat":5, "sun":6}for key, val = range m { h(key, val)}// key == last map key encountered in iteration// val == map[key]var ch chan Work = producer()for w := range ch { doWork(w)}// empty a channelfor range ch {}

Go 语句

go语句表示启动一条独立的线程或goroutine

GoStmt = "go" Expressiongo Server()go func(ch chan<- bool) { for { sleep(10); ch <- true; }} (c)

Select 语句

select 语句 监听channel上的数据流动,并处理发送和接收数据的操作

var a []intvar c, c1, c2, c3, c4 chan intvar i1, i2 intselect {case i1 = <-c1:    print("received ", i1, " from c1\n")case c2 <- i2:    print("sent ", i2, " to c2\n")case i3, ok := (<-c3):  // same as: i3, ok := <-c3    if ok {        print("received ", i3, " from c3\n")    } else {        print("c3 is closed\n")    }case a[f()] = <-c4:    // same as:    // case t := <-c4    //  a[f()] = tdefault:    print("no communication\n")}for {  // send random sequence of bits to c    select {    case c <- 0:  // note: no statement, no fallthrough, no folding of cases    case c <- 1:    }}select {}  // block forever

延迟执行语句

DeferStmt = "defer" Expression .
lock(l)defer unlock(l)  // unlocking happens before surrounding function returns// prints 3 2 1 0 before surrounding function returnsfor i := 0; i <= 3; i++ {    defer fmt.Print(i)}// f returns 1func f() (result int) {    defer func() {        result++    }()    return 0}

错误类型

预定义的error接口

type error interface {    Error() string}

其他考虑事项

数值类型大小

type                                 size in bytesbyte, uint8, int8                     1uint16, int16                         2uint32, int32, float32                4uint64, int64, float64, complex64     8complex128

转载地址:http://cglbi.baihongyu.com/

你可能感兴趣的文章
[茶余饭后]10大毕业生必听得歌曲
查看>>
gdb调试命令的三种调试方式和简单命令介绍
查看>>
C++程序员的几种境界
查看>>
VC++ MFC SQL ADO数据库访问技术使用的基本步骤及方法
查看>>
VUE-Vue.js之$refs,父组件访问、修改子组件中 的数据
查看>>
Vue-子组件改变父级组件的信息
查看>>
Python自动化之pytest常用插件
查看>>
Python自动化之pytest框架使用详解
查看>>
【正则表达式】以个人的理解帮助大家认识正则表达式
查看>>
性能调优之iostat命令详解
查看>>
性能调优之iftop命令详解
查看>>
非关系型数据库(nosql)介绍
查看>>
移动端自动化测试-Windows-Android-Appium环境搭建
查看>>
Xpath使用方法
查看>>
移动端自动化测试-Mac-IOS-Appium环境搭建
查看>>
Selenium之前世今生
查看>>
Selenium-WebDriverApi接口详解
查看>>
Selenium-ActionChains Api接口详解
查看>>
Selenium-Switch与SelectApi接口详解
查看>>
Selenium-Css Selector使用方法
查看>>