array vs slice in Golang
array
The traits of array
- Fixed-length (zero or more), once declared, we can’t change the size
- Sequence of elements (with particular type)
- Seldom used, slice is more common.
- We can compare it using
==
. - Passed by value, means array value will be copied to the corresponding parameter variable.
- Use pointer if we want to pass array by reference
One practical example is SHA digest data structure: sha256.go
package sha256
// ... omitted for brevity
// Sum256 returns the SHA256 checksum of the data.
func Sum256(data []byte) [Size]byte {
var d digest
d.Reset()
d.Write(data)
return d.checkSum()
}
slice
The traits of slice
- Sequence with variable-length, with the same type
- It has 3 components
- pointer (to underlying backend array)
- length
- capacity
- We can’t compare it using
==
. To perform slice comparison, we need to write our own function, except for bytes.Equal - Use
append
function to add elements to slice.
Read The Go Programming Language chapter 4.1 and 4.2 for more details :)