More types structs, slices, and maps.

了解 Golang 有哪些進階型態. 官網上的 More types

Pointers

Go has pointers. A pointer holds the memory address of a value. The type *T is a pointer to a T value. Its zero value is nil.

 1package main
 2import "fmt"
 3
 4func main() {
 5  var p *int
 6  fmt.Println(p) // <nil>  
 7  i := 100
 8  p = &i
 9  fmt.Println(p) // 0xc0000be020
10  *p = 21
11  fmt.Println(i) // 21
12}

Structs

用結構來定義同類型的屬性/欄位.

 1package main
 2import "fmt"
 3
 4type Vertex struct {
 5  X int
 6  Y int
 7}
 8
 9func main() {
10  v := Vertex{}
11  v.X = 4
12  fmt.Printf("v.X=%d, v.Y=%d", v.X, v.Y)
13}

Array and Slices

 1package main
 2import "fmt"
 3
 4func main() {
 5  # array
 6  primes := [6]int{2, 3, 5, 7, 11, 13}
 7  fmt.Println(primes)
 8
 9  # slices
10  var s []int = primes[1:4]
11  fmt.Println(s)
12}

這邊要注意切片會取得陣列的指標, 而不是重新賦予值. 所以

 1package main
 2import "fmt"
 3
 4func main() {
 5  s := []int{2, 3, 5, 7, 11, 13}
 6
 7  t := s[1:3]
 8  fmt.Printf("len:%d, cap:%d, content:%v, %p\n", len(t), cap(t), t, t)
 9    // len:2, cap:5, content:[3 5], 0xc00007a038
10  
11  t = t[:]
12  fmt.Printf("len:%d, cap:%d, content:%v, %p\n", len(t), cap(t), t, t)
13  // len:6, cap:6, content:[2 3 5 7 11 13], 0xc00007a030
14
15  t = t[1:3]
16  fmt.Printf("len:%d, cap:%d, content:%v, %p\n", len(t), cap(t), t, t)
17  // len:2, cap:5, content:[3 5], 0xc00007a038
18  
19  fmt.Printf("%v, %p\n",s[:4],s[:4])
20  // [2 3 5 7], 0xc00007a030, 超過 t 的 len and capality
21  
22  t[1] = 0
23  fmt.Printf("%v, %p",s[:4],s[:4])
24  // [2 3 0 7], 0xc00007a030, array s also change
25}

Nil

  • Nil 很特別並不是關鍵字
  • 不同類型的 nil 都只到同一個記憶體位置
  • 不同類型的 nil 不能比較, 轉型後做比較為 false
 1package main
 2import "fmt"
 3
 4func main() {
 5  var s func()
 6  fmt.Printf("%p\n",s) // 0x0
 7
 8  var a *int
 9  fmt.Printf("%p\n", a) // 0x0
10
11  fmt.Println( s == nil ) // true
12  fmt.Println( a == nil ) // true
13    fmt.Println( (interface{})(s) == (interface{})(a) ) // false
14  fmt.Println( (interface{})(nil) == (*int)(nil) ) // false
15}

Maps

key-value 結構

 1package main
 2import "fmt"
 3
 4func main() {
 5  m := make(map[string]int)
 6
 7  m["Answer"] = 42
 8  fmt.Println("The value:", m["Answer"])
 9
10  m["Answer"] = 48
11  fmt.Println("The value:", m["Answer"])
12
13  delete(m, "Answer")
14  fmt.Println("The value:", m["Answer"])
15
16  v, ok := m["Answer"]
17  fmt.Println("The value:", v, "Present?", ok)
18}

Function closures

 1package main
 2import "fmt"
 3
 4func fibonacci() func() int {
 5  p := 0
 6  pp := 0
 7  sum := 0
 8  return func() int {
 9    sum = p + pp
10    p = pp
11    pp = sum
12    if sum == 0 {
13      p = 1
14    }
15    return sum
16  }
17}
18
19func main() {
20  f := fibonacci()
21  for i := 0; i < 10; i++ {
22    fmt.Println(f())
23  }
24}

References

comments powered by Disqus