Go Slices
- Slices in Go are more powerful and flexible than arrays. While both are used to store multiple values of the same type, slices offer dynamic sizing—they can grow or shrink as needed.
- Unlike arrays, the length of a slice is not fixed, making them more versatile in real-world applications.
Creating Slices
- There are several ways to create a slice in Go:
1.Using the literal syntax
nums := []int{1, 2, 3, 4}
2.Slicing an existing array
arr := [5]int{10, 20, 30, 40, 50}
slice := arr[1:4] // [20 30 40]
3.Using the make() function
slice := make([]int, 3) // Creates a slice with length 3 and capacity 3
Creating a Slice With Literal Syntax
- You can declare a slice in Go with the literal form:
sliceName := []datatype{values}
Empty slice
mySlice := []int{}
- This produces a slice whose length is 0 and capacity is 0.
Pre‑initialized slice
mySlice := []int{1, 2, 3}
- Here, both the length and capacity of mySlice are 3, because three elements are provided at declaration time.
Inspecting a slice
- Go’s standard library provides two built‑in functions to examine a slice:
- These utilities make it easy to check how much data a slice currently holds and how much room it still has to expand.
Example:
package main
import "fmt"
func main() {
// Empty slice of ints
nums := []int{}
fmt.Println(len(nums)) // length
fmt.Println(cap(nums)) // capacity
fmt.Println(nums) // contents
// Pre‑populated slice of strings
words := []string{"Learning", "Go", "is", "fun"}
fmt.Println(len(words)) // length
fmt.Println(cap(words)) // capacity
fmt.Println(words) // contents
}
Output:
0
0
[]
4
4
[Learning Go is fun]
Building a Slice from an Existing Array
- You can carve out a section of an array and treat it as its own slice. The general pattern looks like this:
var myArray = [length]datatype{values} // declare an array
mySlice := myArray[start:end] // create a slice from that array
- start is the index where the slice begins (inclusive).
- end is the index where the slice stops (exclusive).
- The slice’s length is end - start.
- Its capacity is the distance from start to the end of the original array.
Example:
package main
import "fmt"
func main() {
arr := [6]int{10, 11, 12, 13, 14, 15}
sub := arr[2:4] // pulls out elements at index 2 and 3
fmt.Printf("sub = %v\n", sub)
fmt.Printf("len = %d\n", len(sub))
fmt.Printf("capacity = %d\n", cap(sub))
}
Output:
sub = [12 13]
len = 2
capacity = 4
- Here, the slice sub starts at index 2 (12) and ends just before index 4, so it contains [12 13]. Its length is 2, and its capacity is 4 because there are four elements (12 13 14 15) from index 2 to the array’s end.
Creating Slices with make():
- Go’s built‑in make() function lets you allocate a slice directly—handy when you need a slice of a specific length and, optionally, extra capacity for future growth.
sliceName := make([]T, length, capacity)
Parameter Purpose
T The type of elements stored in the slice.
length The initial number of elements (all zero‑valued).
capacity (optional) The total space reserved in the underlying array. If omitted, it defaults to length.
If you leave out the capacity, the slice’s capacity equals its length:
- numbers := make([]int, 5) // length = 5, capacity = 5
Specifying a larger capacity allows the slice to grow without reallocating:
- buffer := make([]byte, 0, 64) // length = 0, capacity = 64
Building a Slice with make()
- The make() function lets you allocate and initialize a slice without first declaring an underlying array.
General form
sliceName := make([]ElementType, length, capacity)
- length – the number of elements the slice initially contains
- capacity – the total space that’s been reserved (optional; if you leave it out, capacity = length)
Example:
package main
import "fmt"
func main() {
// length 5, capacity 10
myslice1 := make([]int, 5, 10)
fmt.Printf("myslice1 = %v\n", myslice1)
fmt.Printf("length = %d\n", len(myslice1))
fmt.Printf("capacity = %d\n", cap(myslice1))
// capacity omitted — defaults to length (5)
myslice2 := make([]int, 5)
fmt.Printf("myslice2 = %v\n", myslice2)
fmt.Printf("length = %d\n", len(myslice2))
fmt.Printf("capacity = %d\n", cap(myslice2))
}
Output:
myslice1 = [0 0 0 0 0]
length = 5
capacity = 10
myslice2 = [0 0 0 0 0]
length = 5
capacity = 5
- Here, myslice1 starts with five zero‑valued integers but has room to grow to ten without reallocation, whereas myslice2 has no spare capacity beyond its initial length.