This is a creation in Article, where the information may have evolved or changed.
Key words
break default func interface selectcase defer go map structchan else goto package switchconst fallthrough if range typecontinue for import return var
Built constants:
true false iota nil
Built-in type:
int int8 int16 int32 int64uint uint8 uint16 uint32 uint64 uintptrfloat32 float64 complex128 complex64bool byte rune string error
Built-in functions:
make len cap new append copy close deletecomplex real imagpanic recover
Statement
var i = 1000func main() {}const PI = 3.141592653589793 type Model struct {}
Variable
var 名字 类型 = 表达式
Pointer
取地址 p := &x解引用 *p = 2
Some data types
Array
// 字面量array := [5]int{1,2,3,4,5}
Slice
Map
var myMap map[keyType]valueTypemake(map[keyType]valueType, 100)myMap = map[keyType]valueTyep {}
New
new(类型) 返回该类型的一个指针p := new(int)```go# 生命周期包级的变量和程序的生命周期一致局部变量不再被引用时自动销毁 # 流程控制## if else```gofunc example(x int) int { if x == 0 { return 5 } else { return x }}
Switch case Default Fallthrough
switch i { case 0: fmt.Printf("0") case 1: fmt.Printf("1") case 2: fallthrough case 3: fmt.Printf("3") case 4, 5, 6: fmt.Printf("4, 5, 6") default: fmt.Printf("Default")}
For break continue
Normal for loop
sum := 0for i := 0; i < 10; i++ { sum += i } a := []int{1, 2, 3, 4, 5, 6}for i, j := 0, len(a) – 1; i < j; i, j = i + 1, j – 1 { a[i], a[j] = a[j], a[i]}
Imitate while (go without while, do-while)
sum := 0 for { sum++ if sum > 100 { break } }
Break jump
for j := 0; j < 5; j++ { for i := 0; i < 10; i++ { if i > 5 { break JLoop } fmt.Println(i) } }JLoop: // ...
Goto
Interface
Interface Reader {
Read ()
}
Function
Defer func1 ()
Defer Func2 ()
Advanced after out, so first execute FUNC2, then execute func1
Goroutine
Start a goroutine (go concurrency)
go f()
Create a channel (communication mechanism for GO)
ch = make(chan int)ch = make(chan int, 3) // 带缓冲
Receive
x = <-ch // 从ch接收数据,并保存在x
Send
ch <- x // 将x的内容发送到ch
Shut down
close(ch)
Multiplexing
select {case <-CH1://Case x: = <-CH2://FMT. PRINTLN (x) case CH3 <-y://default://}