capypad
0 day streak
go / beginner
Snippet

Working with Slices

Slices are dynamic, growable sequences in Go. Unlike arrays, slices can change size. The `append` function adds elements and automatically grows the underlying array when needed. `len()` returns the number of elements, `cap()` returns the underlying array's capacity.

snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
package main
 
import "fmt"
 
func main() {
nums := []int{10, 20, 30}
nums = append(nums, 40)
fmt.Println("Length:", len(nums))
fmt.Println("Capacity:", cap(nums))
fmt.Println("Third element:", nums[2])
}
Breakdown
1
nums := []int{10, 20, 30}
Creates a slice with three integers using composite literal syntax
2
append(nums, 40)
Adds 40 to the slice, automatically resizing if capacity is exceeded
3
len(nums) / cap(nums)
len returns element count, cap returns underlying array capacity