Go Slices and Arrays
Working with arrays and slices in Go
Arrays
var arr [5]int # fixed size array
arr2 := [3]string{"a", "b", "c"} # initialize array
arr3 := [...]int{1, 2, 3} # infer length
value := arr[0] # access element
length := len(arr) # get length
Slices
slice := []int{1, 2, 3} # create slice
empty := make([]int, 5) # make slice with length 5
withCap := make([]int, 5, 10) # length 5, capacity 10
Slice Operations
slice = append(slice, 4) # add element
slice = append(slice, 5, 6) # add multiple
sub := slice[1:3] # slice from index 1 to 2
first := slice[:2] # first 2 elements
last := slice[2:] # from index 2 to end
Length and Capacity
length := len(slice) # number of elements
capacity := cap(slice) # total capacity
Copy Slices
src := []int{1, 2, 3}
dst := make([]int, len(src))
copy(dst, src) # copy elements from src to dst