go / beginner
Snippet
Slices: Dynamic Arrays in Go
Slices are growable dynamic views into arrays. Unlike arrays with fixed size, slices can grow or shrink using append(). The make() function creates a slice with pre-allocated capacity. Slicing with [start:end] creates a new view (reference) into the same underlying array.
snippet.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package mainimport "fmt"func main() {names := []string{"Alice", "Bob"}fmt.Printf("Initial: %v, Length: %d, Capacity: %d\n", names, len(names), cap(names))names = append(names, "Charlie")fmt.Printf("After append: %v, Length: %d, Capacity: %d\n", names, len(names), cap(names))slice := make([]int, 0, 5)slice = append(slice, 10, 20, 30)fmt.Printf("Made slice: %v\n", slice)sub := slice[1:3]fmt.Printf("Sub-slice [1:3]: %v\n", sub)}
Breakdown
1
names := []string{"Alice", "Bob"}
Composite literal syntax creates a slice with two elements
2
append(names, "Charlie")
append() adds elements and may reallocate if capacity is exceeded
3
make([]int, 0, 5)
make(type, length, capacity) pre-allocates capacity without initializing elements
4
slice[1:3]
Slice expression creates a sub-view from index 1 inclusive to 3 exclusive