A Tour of GO (3)--More Types

  1. Pointers
    • *T is type: a pointer to T.
      var x *int
    • Operator & generate a pointer to its operand
      i :=42
      p =&i
    • The * operator denote the pointer's underlying value.
      i = 43
      fmt. Println(
      i)
  2. Struct
    type Vertex struct{
    X int
    Y int
    }
  • Fields are accessed using dot.
  • Struct fields can be accessed through pointers and dot.
    v := Vertext {1,2}
    p = &v
    p.X = 10
  • Struct literals denote the fields of the struct by listing. You can specify only part of them using Name: syntax.
    v1 = Vertex{1, 2} // has type Vertex
    v2 = Vertex{X: 1} // Y:0 is implicit
    v3 = Vertex{} // X:0 and Y:0
    p = &Vertex{1, 2} // has type *Vertex
  1. Array
    The type [n]T is an array of n values of type T
  • The size of an array is part of its type. So it cannot be resized *

  • Slice: a slice points to an array of values and also include a length.

    • []T is a slice of type T

    • len(s) return the length of slice s.

    • Slice can be nested( slice of slices).

    • Slicing slices: Slices can be re-sliced, creating a new slice value that points to the same array.
      s[lo:hi] evaluate slice from lo to hi-1 inclusively.

    • Make slices:
      a := make([]int, 5) // len(a)=5
      b := make([]int, 0, 5) // len(b)=0, cap(b)=5

    • Zero of slice is nil

    • Adding elements to slice.
      func append(s []T, vs ...T) []T

    • Range is a form of for loop. Two values are used. The first one is the index and the second is the value in the array.

       var pow = []int{1, 2, 4, 8, 16, 32, 64, 128}
      
       func main() {
          for i, v := range pow {
             fmt.Printf("2**%d = %d\n", i, v)
          }
       }
      

      You can skip the index or value by assigning to _.
      pow := make([]int, 10)
      for i := range pow {
      pow[i] = 1 << uint(i)
      }
      for _, value := range pow {
      fmt.Printf("%d\n", value)
      }

  1. Map
  • Map must be created with make before used
  • var m = map[sting] Vertex key is of type string and value is of type Vertex.
  • Mutating maps:
    • Insert
      m[key]=elem
    • Retrieve
      elem= m[key]
    • Delete
      delete (m , key)
    • Test existence
      elem, ok = m[key]
      if the key is in m, ok is true. IF key is not in m, elem is the zero value of that type.
  1. Function values
    Go functions may be closures. A closure is a function value that references variables from outside its body. The function may access and assign to the referenced variables; in this sense the function is "bound" to the variables.
func adder() func(int) int {
  sum := 0
  return func(x int) int {
    sum += x  
    return sum
  }
}

func main() {
  pos, neg := adder(), adder()
  for i := 0; i < 10; i++ {
    fmt.Println(
        pos(i),
        neg(-2*i),
    )   
  }
}

你可能感兴趣的:(A Tour of GO (3)--More Types)