DEV Community

jguo
jguo

Posted on

Learning Golang 104

Data

Go has two allocation primitives, the built-in functions new and make.

Allocation with new

it allocates memory, but it does not initialize the memory, it only zeros it (default value. check the definition here). It returns a pointer to a newly allocated zero value of type.
For example:

type SyncedBuffer struct {
    lock    sync.Mutex
    buffer  bytes.Buffer
}

p := new(SyncedBuffer)  // type *SyncedBuffer
var v SyncedBuffer      // type  SyncedBuffer
Enter fullscreen mode Exit fullscreen mode

Constructors and composite literals
Sometimes the zero value isn't good enough and an initializing constructor is necessary.

func NewFile(fd int, name string) *File {
    if fd < 0 {
        return nil
    }
     return &File{fd: fd, name: name}
}
Enter fullscreen mode Exit fullscreen mode

If a composite literal contains no fields at all, it creates a zero value for the type. The expressions new(File) and &File{} are equivalent.

Allocation with make

Make applies only to maps, slices and channels and does not return a pointer. The reason is that these three types must be initialized before use. It returns an initialized (not zeroed) value of type T (not *T).

Arrays

Keynote

  • Arrays are values. Assigning one array to another copies all the elements.
  • In particular, if you pass an array to a function, it will receive a copy of the array, not a pointer to it.
  • The size of an array is part of its type. The types [10]int and [20]int are distinct.
Do pass value, instead using point. value is expensive.
func Sum(a *[3]float64) (sum float64) {
    for _, v := range *a {
        sum += v
    }
    return
}

array := [...]float64{7.0, 8.5, 9.1}
x := Sum(&array)  // Note the explicit address-of operator
Enter fullscreen mode Exit fullscreen mode

Slice

Slices wrap arrays to give a more general, powerful, and convenient interface to sequences of data. Slices hold references to an underlying array, and if you assign one slice to another, both refer to the same array.

func (f *File) Read(buf []byte) (n int, err error)

n, err := f.Read(buf[0:32]) // read first 32 bytes
Enter fullscreen mode Exit fullscreen mode

Maps

Key-Value pair

var timeZone = map[string]int{
    "UTC":  0*60*60,
    "EST": -5*60*60,
    "CST": -6*60*60,
    "MST": -7*60*60,
    "PST": -8*60*60,
}
Enter fullscreen mode Exit fullscreen mode

timeZone[key] returns two values. First one is the value, second one is bool, false if not present. true if present.

Top comments (0)