Slices
Slices are a key data type in Go, providing a more powerful interface to sequences than arrays. Unlike arrays, slices are dynamically-sized and flexible.
Key Points
- Slices are reference types that point to an underlying array
- Modifying a slice modifies the underlying array
- Multiple slices can share the same underlying array
appendmay allocate a new array if capacity is exceeded- Use
makewith capacity when size is known for better performance - Nil slices can be appended to and work with most operations
- Slicing doesn't copy data, it creates a new slice header
Creating Slices
Slices can be created in multiple ways:
package main
import "fmt"
func main() {
// Create a slice with make
s := make([]string, 3)
fmt.Println("empty:", s)
// Set and get values
s[0] = "a"
s[1] = "b"
s[2] = "c"
fmt.Println("set:", s)
fmt.Println("get:", s[2])
// Length of slice
fmt.Println("len:", len(s))
// Append to slice
s = append(s, "d")
s = append(s, "e", "f")
fmt.Println("appended:", s)
// Copy slice
c := make([]string, len(s))
copy(c, s)
fmt.Println("copied:", c)
}empty: [ ]
set: [a b c]
get: c
len: 3
appended: [a b c d e f]
copied: [a b c d e f]Slice Operator
Slices support a "slice" operator with the syntax slice[low:high]:
package main
import "fmt"
func main() {
s := []string{"a", "b", "c", "d", "e", "f"}
// Get elements from index 2 to 5
fmt.Println("sl1:", s[2:5])
// Get elements up to index 5
fmt.Println("sl2:", s[:5])
// Get elements from index 2 onwards
fmt.Println("sl3:", s[2:])
}sl1: [c d e]
sl2: [a b c d e]
sl3: [c d e f]Slice Literals
You can declare and initialize a slice in one line:
package main
import "fmt"
func main() {
// Slice literal
t := []string{"g", "h", "i"}
fmt.Println("slice literal:", t)
// Multi-dimensional slice
twoD := make([][]int, 3)
for i := 0; i < 3; i++ {
innerLen := i + 1
twoD[i] = make([]int, innerLen)
for j := 0; j < innerLen; j++ {
twoD[i][j] = i + j
}
}
fmt.Println("2d: ", twoD)
}slice literal: [g h i]
2d: [[0] [1 2] [2 3 4]]Slice Declaration Patterns
| Pattern | Example | Description |
|---|---|---|
make([]T, length) | make([]int, 5) | Create slice with length, zero values |
make([]T, length, capacity) | make([]int, 5, 10) | Create slice with length and capacity |
[]T{values} | []int{1, 2, 3} | Slice literal with values |
var s []T | var s []int | Declare nil slice |
array[:] | arr[:] | Create slice from entire array |
slice[low:high] | s[1:3] | Create slice from slice (subslice) |
Slice Operations
| Operation | Syntax | Example | Description |
|---|---|---|---|
| Length | len(s) | len(s) | Returns number of elements |
| Capacity | cap(s) | cap(s) | Returns capacity of underlying array |
| Append | append(s, elements...) | append(s, 1, 2, 3) | Add elements to end of slice |
| Copy | copy(dst, src) | copy(dst, src) | Copy elements from src to dst |
| Slice | s[low:high] | s[1:3] | Create subslice from index low to high-1 |
| Iterate | for i, v := range s | for i, v := range s | Loop through index and value |
| Access | s[index] | s[0] | Get or set element at index |
Slice Internals
| Concept | Description | Notes |
|---|---|---|
| Length | Number of elements in the slice | Can be less than or equal to capacity |
| Capacity | Size of underlying array from first element | Maximum size before reallocation |
| Pointer | Reference to first element of slice | Slices are reference types |
| Nil slice | Zero value of a slice | len=0, cap=0, pointer=nil |
| Empty slice | Slice with length 0 but allocated | make([]T, 0) or []T{} |
| Growth | Capacity doubles when append exceeds capacity | Automatic reallocation and copy |
Common Patterns
| Pattern | Code | Use Case |
|---|---|---|
| Pre-allocate | s := make([]T, 0, capacity) | When you know approximate size |
| Append slice | s = append(s, other...) | Concatenate two slices |
| Remove element | s = append(s[:i], s[i+1:]...) | Remove element at index i |
| Insert element | s = append(s[:i], append([]T{x}, s[i:]...)...) | Insert x at index i |
| Clear slice | s = s[:0] | Keep capacity, reset length |
| Filter in place | s = s[:0]; for _, x := range original { if keep(x) { s = append(s, x) } } | Efficient filtering |