In Go, slices are a powerful and flexible way to work with sequences of elements. Unlike arrays, slices are dynamically sized and provide many convenient features for handling collections of data.
A slice is a descriptor of an array segment. It consists of:
Unlike arrays, slices donβt have a fixed size, so they can grow or shrink as needed.
var numbers []int // Declares a slice of ints, initially nil colors := []string{"red", "green", "blue"} // Declares and initializes a slice
You can create slices with a specified length and capacity using make()
:
s := make([]int, 5) // Length 5, capacity 5, all elements initialized to 0 s2 := make([]int, 3, 10) // Length 3, capacity 10
You can access or update slice elements using indices:
colors := []string{"red", "green", "blue"} fmt.Println(colors[1]) // Output: green colors[2] = "yellow" fmt.Println(colors) // Output: [red green yellow]
You can create new slices by slicing existing slices or arrays:
nums := []int{1, 2, 3, 4, 5} subslice := nums[1:4] // Elements from index 1 to 3 β [2 3 4] fmt.Println(subslice)
You can add elements dynamically using the built-in append()
function. If the sliceβs capacity is exceeded, Go automatically allocates a new underlying array.
var nums []int // nil slice nums = append(nums, 1) // [1] nums = append(nums, 2, 3) // [1 2 3] fmt.Println(nums)
Use len()
to get the number of elements and cap()
for the capacity of the slice:
s := make([]int, 3, 5) fmt.Println("Length:", len(s)) // 3 fmt.Println("Capacity:", cap(s)) // 5
append()
to grow slices dynamically.Slices are the idiomatic way to work with collections in Go. They offer flexibility, dynamic sizing, and convenient built-in functions that make them more powerful than arrays in most cases.
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!