Golang学习笔记:语言规范二

类型转换

形式为 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 int
func()(x)        // function signature func() x
(func())(x)      // x is converted to func()
(func() int)(x)  // x is converted to func() int
func() int(x)    // x is converted to func() int (unambiguous)

常量转换

uint(iota)               // iota value of type uint
float32(2.718281828)     // 2.718281828 of type float32
complex128(1)            // 1.0 + 0.0i of type complex128
float32(0.49999999)      // 0.5 of type float32
string('x')              // "x" of type string
string(0x266c)           // "♬" of type string
MyString("foo" + "bar")  // "foobar" of type MyString
string([]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 type
int(1.2)                 // illegal: 1.2 cannot be represented as an int
string(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 string
MyString(0x65e5)  // "\u65e5" == "日" == "\xe6\x97\xa5"

转换byte类型的slice为字符串

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

type MyBytes []byte
string(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 []rune
string(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    Assignment
x++                 x += 1
x--                 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 -x
default: 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 int
case float64:
    printFloat64(i)                        // type of i is float64
case func(int) float64:
    printFunction(i)                       // type of i is func(int) float64
case 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]string
for i, s := range a {
    // type of i is int
    // type of s is string
    // s == a[i]
    g(i, s)
}

var key string
var val interface {}  // value type of m is assignable to val
m := 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 channel
for range ch {}

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

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

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

var a []int
var c, c1, c2, c3, c4 chan int
var i1, i2 int
select {
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()] = t
default:
    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 returns
for i := 0; i <= 3; i++ {
    defer fmt.Print(i)
}

// f returns 1
func f() (result int) {
    defer func() {
        result++
    }()
    return 0
}

错误类型

预定义的error接口

type error interface { Error() string }

其他考虑事项

数值类型大小

type                                 size in bytes

byte, uint8, int8                     1
uint16, int16                         2
uint32, int32, float32                4
uint64, int64, float64, complex64     8
complex128        

你可能感兴趣的:(golang,语言规范)