append, copy and slice capacity
An array cannot grow, but a slice can, thanks to the built-in append function. It is the operation you will use most with lists: adding elements at the end. Behind its apparent simplicity there is an important memory detail that, if you do not know it, produces very hard-to-find bugs. Today we will see how append works, what happens with capacity, how to create independent copies with copy and how to remove or insert elements in the middle of a slice.
append
append(s, x, y) returns a slice with the added elements. It is essential to store the result: s = append(s, 4). The reason is that, if the slice still has free capacity, append reuses the same array and only increases the length; but if capacity runs out, Go allocates a new bigger array (usually doubling capacity for small slices), copies the elements and returns a slice pointing to the new array. That is why the result can differ from the original. To add all the elements of another slice use three dots: append(a, b...).
package main
import "fmt"
func main() {
var s []int // nil slice
for i := 1; i <= 6; i++ {
s = append(s, i)
fmt.Println(len(s), cap(s)) // capacity grows as needed
}
a := []int{1, 2}
b := []int{3, 4}
a = append(a, b...)
fmt.Println(a) // [1 2 3 4]
// preallocate when you know the size
n := 1000
data := make([]int, 0, n) // len 0, cap 1000
for i := 0; i < n; i++ {
data = append(data, i)
}
fmt.Println(len(data), cap(data)) // 1000 1000
}The danger of shared memory
If you have a sub-slice with spare capacity and you append, you can overwrite elements of the original slice without noticing. It is the classic bug. For example, base[:2] has length 2 but larger capacity: when you append an element to it, it is written at position 2 of the shared array, overwriting the value base had there. To avoid it there is the three-index expression s[a:b:c], which also limits the capacity, or you create an independent copy. The safe rule is: if you are going to modify a slice you received from elsewhere, copy it first.
package main
import "fmt"
func main() {
base := []int{1, 2, 3, 4}
part := base[:2]
part = append(part, 99) // overwrites base[2]!
fmt.Println(base, part) // [1 2 99 4] [1 2 99]
// safe: limit the capacity with a third index
base2 := []int{1, 2, 3, 4}
safe := base2[:2:2]
safe = append(safe, 99) // forces a new array
fmt.Println(base2, safe) // [1 2 3 4] [1 2 99]
// independent copy with copy
src := []int{7, 8, 9}
dst := make([]int, len(src))
n := copy(dst, src)
dst[0] = 0
fmt.Println(n, src, dst) // 3 [7 8 9] [0 8 9]
}Removing and inserting
copy(dst, src) copies as many elements as fit in the destination and returns the number copied. Go has no method to delete elements from the middle, but it is solved with append: to remove element i you write s = append(s[:i], s[i+1:]...). The slices package of the standard library (since Go 1.21) brings ready functions for this: slices.Delete, slices.Insert, slices.Contains, slices.Sort, slices.Index and slices.Reverse. When they exist, they are preferable to writing them by hand, because they are clearer and tested.
package main
import (
"fmt"
"slices"
)
func main() {
names := []string{"bob", "ana", "carl", "dina"}
slices.Sort(names)
fmt.Println(names) // [ana bob carl dina]
fmt.Println(slices.Contains(names, "carl"), slices.Index(names, "dina")) // true 3
names = slices.Delete(names, 1, 2) // removes index 1 (bob)
fmt.Println(names) // [ana carl dina]
names = slices.Insert(names, 1, "eve")
fmt.Println(names) // [ana eve carl dina]
}- Always store the result: s = append(s, x).
- Capacity grows by itself, but make with capacity avoids copies.
- append can overwrite data of another slice sharing the array.
- copy creates independent copies.
- The slices package already has Sort, Contains, Index, Insert and Delete.
✎ ملاحظاتي
محفوظ في هذا المتصفح فقط. سجّل الدخول لحفظه في حسابك.0/5000 حرف