[Go] Slices vs Array

It is recommended to use 'slice' over 'Array'. 

An array variable denotes the entire array; it is not a pointer to the first array element (as would be the case in C). This means that when you assign or pass around an array value you will make a copy of its contents.

Arrays have their place, but they're a bit inflexible, so you don't see them too often in Go code. Slices, though, are everywhere. They build on arrays to provide great power and convenience.

letters := []string{"a", "b", "c", "d"}

You can call built-in function:

var s []byte
s = make([]byte, 5, 5)
// s == []byte{0, 0, 0, 0, 0}

When you modifiy the slices, it pass around the reference:

d := []byte{'r', 'o', 'a', 'd'}
e := d[2:] 
// e == []byte{'a', 'd'}
e[1] = 'm'
// e == []byte{'a', 'm'}
// d == []byte{'r', 'o', 'a', 'm'}

More information: https://blog.golang.org/go-slices-usage-and-internals

原文地址:https://www.cnblogs.com/Answer1215/p/11842606.html