0%

Go_Learning_Fundamental_Allocation

Allocation

Three allocation methods in Go language, new make composite literals; While new and make are build in functions, composite literals is a kind of initialise format. Different allocation method with different feature.

new: build in function, allocate memory , zeros it, ,return the pointer(*T) of type T.

  • Apply Type: Any

  • Basic Format: new(type)

    • Zeros struct:

      1
      2
      3
      4
      5
      6
      type SyncedBuffer struct {
      lock sync.Mutex
      buffer bytes.Buffer
      }
      var p *SyncedBuffer = new(SyncedBuffer) // type *SyncedBuffer
      p := new(SyncedBuffer) // type *SyncedBuffer
    • Zeros slice:

      1
      2
      var p *[]int = new([]int)       // allocates slice structure; *p == nil; 
      p := new([]int) //allocates slice structure; *p == nil;

make:build in function, allocate memory, initialized it, return the value(T) of type T .

  • Aapply Type: only slices, maps, channels

  • Basic Format: make(type , length , capacity)

    • Initialized Slice:

      A slice, for example, is a three-item descriptor containing a pointer to the data (inside an array), the length, and the capacity, and until those items are initialized, the slice is nil.

      1
      make([]int, 10, 100)

      allocates an array of 100 ints and then creates a slice structure with length 10 and a capacity of 100 pointing at the first 10 elements of the array. When making a slice, the capacity can be omitted;

composite literals: a kind of initialise format, allocate memory, initialized it , return the value(T) of type T

  • Apply Type: Any

  • Basic Format: Type{value_0, ..., value_n} or Type{item_y : value_x, item_x: value_x, ... }

    • Initialized Slice:

      1
      2
      // TODO: figure out 
      s := []string {Enone: "no error", Eio: "Eio", Einval: "invalid argument"}
    • Initialized Struct:

      1
      2
      3
      4
      5
      6
      7
      8
      9
      func NewFile(fd int, name string) *File {
      if fd < 0 {
      return nil
      }
      f := File{fd, name, nil, 0}
      return &f
      // equals to: return &File{fd, name, nil, 0}
      // equals to: return &File{fd: fd, name: name}
      }