Slice#
[]int is a type.
eg.
var x []intNil vs Empty Slice#
Nil Slice#
eg.
var x []int
fmt.Println(x == nil) // trueEmpty Slice#
eg.
y := []int{}
fmt.Println(y == nil) // false
z := []int(nil)
fmt.Println(z == nil) // trueDifferences#
nilslice: No memory allocation, JSON encodes tonull.- Empty slice: Memory allocated for header, JSON encodes to
[].
Append to Nil Slice#
A nil slice is appendable. append will allocate a new underlying array if the slice is nil.
eg.
var x []int
x = append(x, 1)
fmt.Println(x) // [1]Pass-by-Value (Header)#
When a slice is passed to a function, the slice header (pointer, length, capacity) is copied.
- Modifying elements: Works, as the pointer to the underlying array is shared.
- Lengthening (eg.
append): Does not work for the caller, as the length in the caller’s header is not updated.
Any modification to the slice’s contents is reflected in the original variable, but using append to change the length isn’t reflected in the original variable, even if the slice has a capacity greater than its length.
If the called function changes the capacity (reallocation), all subsequent changes might not be seen in the calling function.
eg.
func f(s []int) {
s = append(s, 1, 2, 3, 4) // Capacity change (reallocation)
for i := range s {
s[i] = 100
}
fmt.Println("In f(): ", s)
}
func main() {
s := make([]int, 0, 4)
s = append(s, 1, 2, 3, 4)
fmt.Println("Before f(): ", s)
f(s)
fmt.Println("After f(): ", s)
}Before f(): [1 2 3 4]
In f(): [100 100 100 100 100 100 100 100]
After f(): [1 2 3 4]Slice and Array#
Array to Slice#
Use the slicing operator [:].
eg.
a := [3]int{1, 2, 3}
s := a[:]Slice to Array#
Go 1.20+ supports direct conversion from slice to array. This operation copies the elements; the array does not share memory with the slice.
eg.
s := []int{1, 2, 3, 4}
a := [4]int(s)Slice to Pointer to Array#
Go 1.17+ supports conversion from slice to array pointer. This shares the underlying memory.
eg.
s := []int{1, 2, 3, 4}
p := (*[4]int)(s)Pointer to Array to Slice#
Use the slicing operator [:] on the array pointer.
eg.
p := &[4]int{1, 2, 3, 4}
s := p[:]