基本上由 package 組成。
Import Package
多數import
1 2 3 4
| import ( "fmt" "math" )
|
存取修飾
依照package 內首字大寫(Public) 小寫(Private)
命名返回1 2 3 4 5
| func split(sum int) (x, y int) { x = sum * 4 / 9 y = sum - x return }
|
變數宣告
一般宣告以及短聲明1 2 3 4 5 6
| var a,b int var a,b = 1,2 func a() { a := 1 const Truth = true }
|
for 語法
1 2 3 4
| for i := 0; i < 10; i++ {} for ; sum < 1000; {} for sum < 1000 {} for {}
|
if 語法
1 2 3 4 5 6 7 8
| for sum < 1000 { if v := math.Pow(x, n); v < lim {
} else {
} }
|
struct
1 2 3 4 5 6 7 8 9
| type Vertex struct { X, Y int }
&Vertex{1, 2} Vertex{X: 1} var t *T = new(T)
|
Array (固定大小)
1 2 3 4 5 6
| [n]T array []int{2, 3, 5, 7, 11, 13} []T slice make([]int, 5) p == [2 3 5 7 11 13] p[1:4] == [3 5 7] p[:3] == [2 3 5] p[4:] == [11 13]
|
Map (python dict)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| map[string]Vertex{ "Bell Labs": Vertex{ 40.68433, -74.39967, }, "Google": Vertex{ 37.42202, -122.08408, }, }
var m = map[string]Vertex{ "Bell Labs": {40.68433, -74.39967}, "Google": {37.42202, -122.08408}, }
m[key] = elem elem = m[key] delete(m, key) elem, ok = m[key]
|
switch
1 2
| fallthrough case t.Hour() < 12:
|
Method
Define1 2 3 4
| func (v *Vertex) Abs() float64 { return math.Sqrt(v.X*v.X + v.Y*v.Y) }
|
Invoke1 2
| v := &Vertex{3, 4} fmt.Println(v.Abs())
|
Interface
1 2
| v := &Vertex{3, 4} fmt.Println(v.Abs())
|
goroutine (輕量級 Thread)
Channel
1 2 3 4 5 6 7 8 9 10
| ch := make(chan int) 當 ch 接收到值丟給 v v := <-ch
ch := make(chan int, 100) v, ok := <-ch for i := range c close(c)
|
題目
Page 431 2 3 4 5
| strs := strings.Split(s," ") m := map[string]int{} for _,element := range strs { m[element] += 1 }
|
Page 461 2 3 4 5 6
| a := 1 b := 0 return func() int { a,b = b, a+b return b }
|
還沒懂
Page 17, 56