go / beginner
Snippet
Slices: Go's Dynamic Arrays
Slices are growable, dynamic views into arrays. Unlike fixed-size arrays, slices can grow and shrink as needed. The make function creates a slice with a specific length and capacity. You can append elements using the built-in append function, which automatically handles resizing when needed. Slices consist of three components: a pointer to the underlying array, a length (current number of elements), and a capacity (how much it can grow before reallocating).
snippet.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package mainimport "fmt"func main() {// Create a slice with makenumbers := make([]int, 3, 10)fmt.Printf("Length: %d, Capacity: %d\n", len(numbers), cap(numbers))// Append elementsnumbers = append(numbers, 1, 2, 3, 4)fmt.Printf("After append - Length: %d, Capacity: %d\n", len(numbers), cap(numbers))fmt.Println("Contents:", numbers)// Slice literalsfruits := []string{"apple", "banana", "orange"}fmt.Println("Fruits:", fruits)// Sub-slicingsubset := numbers[1:4]fmt.Println("Subset:", subset)}
Breakdown
1
numbers := make([]int, 3, 10)
Creates a slice with length 3 and capacity 10, all elements initialized to zero value (0)
2
append(numbers, 1, 2, 3, 4)
Appends multiple values to the slice, returns a new slice
3
subset := numbers[1:4]
Creates a sub-slice from index 1 (inclusive) to 4 (exclusive)