Junior
How to work with slices in Go?
sobes.tech AI
Answer from AI
Slices in Go are not arrays, but references to a segment (or the whole) of an underlying array. They are dynamic data structures.
Creating a slice:
- From an array:
// defining an array
arr := [5]int{1, 2, 3, 4, 5}
// creating a slice from part of the array
s1 := arr[1:4] // s1 contains elements arr[1], arr[2], arr[3]
// creating a slice from the beginning to index 3
s2 := arr[:3] // s2 contains elements arr[0], arr[1], arr[2]
// creating a slice from index 2 to the end
s3 := arr[2:] // s3 contains elements arr[2], arr[3], arr[4]
// creating a slice of the entire array
s4 := arr[:] // s4 references the whole array
- Using
make:
// Creating a slice with length 5 and capacity 5
s := make([]int, 5)
// Creating a slice with length 5 and capacity 10
s_cap := make([]int, 5, 10)
- By literal:
s := []int{1, 2, 3}
Main properties of a slice:
len(s): returns the current length of the slice.cap(s): returns the capacity of the slice (maximum number of elements before reallocation).
Adding elements (append):
s := []int{1, 2}
s = append(s, 3) // adds one element
s = append(s, 4, 5) // adds multiple elements
s2 := []int{6, 7}
s = append(s, s2...) // adds elements from another slice
append may cause reallocation of the underlying array if capacity is insufficient.
Removing elements:
Removing elements from a slice is achieved by creating a new slice from the remaining elements or copying.
s := []int{1, 2, 3, 4, 5}
// Removing element at index i
i := 2 // removing element at index 2 (which is 3)
s = append(s[:i], s[i+1:]...)
Copying slices:
src := []int{1, 2, 3}
dst := make([]int, len(src))
copy(dst, src) // copies elements from src to dst
copy copies the minimum of the lengths of the two slices.
Iterating over a slice:
s := []string{"a", "b", "c"}
for i, v := range s {
// i - index, v - value
}
for i := range s {
// only index
}
for _, v := range s {
// only value
}
Slices are reference types:
Changes in a slice are reflected in the underlying array and other slices referencing the same memory area.
arr := [5]int{1, 2, 3, 4, 5}
s1 := arr[1:4] // [2, 3, 4]
s2 := arr[2:5] // [3, 4, 5]
s1[0] = 99
// Now arr: [1, 99, 3, 4, 5]
// s1: [99, 3, 4]
// s2: [3, 4, 5] (element arr[2] changed)