Arrays and slices
Until now each variable held a single value. But almost every program works with lists: the prices in a cart, the names of users, the lines of a file. Go offers two types for this. The array has a fixed size that is part of its type. The slice is a flexible view over an array, with variable size, and it is by far the most used structure. In this lesson you will learn what they are, how they are created, how they are cut and why you must understand how they share memory.
Arrays: fixed size
An array is declared with its length between brackets: var scores [3]int creates three integers initialized to zero. [3]int and [4]int are different, incompatible types. Also, arrays are values: assigning an array to another variable or passing it to a function copies it entirely. Because of these limitations, arrays are rarely used directly; they are rather the storage behind slices. They are accessed by index, which starts at 0, and going out of range causes a panic at run time.
Slices: the flexible list
A slice is written []T without a length. You can create it with a literal, []int{1, 2, 3}, or with the make([]int, n) function, which creates n zero elements. Internally a slice holds three pieces of data: a pointer to the underlying array, its length (len, how many elements it has) and its capacity (cap, how many fit before allocating new memory). An uninitialized slice is nil, has length 0 and is perfectly safe to use with len, range and append. The expression s[a:b] produces a sub-slice from a up to b not including b, and shares the same array.
package main
import "fmt"
func main() {
var arr [3]int // fixed size, zero values
arr[0] = 10
copyArr := arr // full copy
copyArr[0] = 99
fmt.Println(arr, copyArr) // [10 0 0] [99 0 0]
nums := []int{10, 20, 30, 40, 50}
fmt.Println(len(nums), cap(nums)) // 5 5
fmt.Println(nums[1:4]) // [20 30 40]
fmt.Println(nums[:2], nums[3:]) // [10 20] [40 50]
zeros := make([]int, 3)
fmt.Println(zeros) // [0 0 0]
var empty []int
fmt.Println(empty == nil, len(empty)) // true 0
}Sub-slices share memory
This is the point that confuses people most at the beginning. A sub-slice does not copy the data: it points to the same array. If you modify an element through one, the change is seen in the other. This is efficient, but it can cause surprises when you pass a slice to a function: the function can modify the elements of your original slice, even though the slice itself is passed by value (the pointer, length and capacity are copied, not the data). If you need an independent copy, you will have to create it explicitly, something we will see in the next lesson.
package main
import "fmt"
func resetFirst(s []int) {
s[0] = 0 // modifies the caller's data
}
func main() {
base := []int{1, 2, 3, 4, 5}
part := base[1:3] // [2 3], same backing array
part[0] = 200
fmt.Println(base) // [1 200 3 4 5]
fmt.Println(len(part), cap(part)) // 2 4
resetFirst(base)
fmt.Println(base) // [0 200 3 4 5]
sum := 0
for _, v := range base {
sum += v
}
fmt.Println(sum) // 212
}- [3]int is an array (fixed size, copied on assignment).
- []int is a slice (variable size, shares memory).
- len(s) is how many elements it has; cap(s) is how many fit without allocating.
- s[a:b] includes a and excludes b.
- A nil slice is safe with len, range and append.
✎ Meine Notizen
Nur in diesem Browser gespeichert. Melde dich an, um es im Konto zu behalten.0/5000 Zeichen