Slices
Basic
A dynamically sized view into an array.
They do not store data, they just reference an array
func main() {
a := [7]int{0, 1, 2, 3, 4, 5, 6}
slice := a[1:4]
a[1] = 2
fmt.Println(slice)
}
// Output: [2 2 3]
A slice can manipulate the underlying data structure
func main() {
a := [7]int{0, 1, 2, 3, 4, 5, 6}
slice := a[1:4]
a[1] = 2
slice[1] = 10
fmt.Println(slice)
}The normal way of defining a slice
This will create an array, then create a slice onto it, which you can then use as a
func main() {
a := []int{0, 1, 2, 3, 4, 5, 6}
fmt.Printf("%T, %v", a, a)
}Access
func main() {
a := []int{0, 1, 2, 3, 4, 5, 6}
fmt.Printf("%v\n", a[:3])
fmt.Printf("%v\n", a[3])
fmt.Printf("%v\n", a[:])
fmt.Printf("%v\n", a)
}
/*
Output:
[0 1 2]
3
[0 1 2 3 4 5 6]
[0 1 2 3 4 5 6]
*/Capacity vs Length
Capacity is the length of the underlying array
The length is just the length of the slice
Note: Thus you can index out of range if you are not looking at the capacity
func main() {
a := []int{0, 1, 2}
fmt.Printf("Length %v\n", len(a))
fmt.Printf("Capacity %v\n", cap(a))
a[10] = 1
}
/*
Output:
Length 3
Capacity 3
panic: runtime error: index out of range [10] with length 3
*/Nil slice
A slice with 0 capacity and length
func main() {
var a []int
fmt.Printf("Length %v\n", len(a))
fmt.Printf("Capacity %v\n", cap(a))
if a == nil {
fmt.Println("Is Nil")
}
}
/*
Output:
Length 0
Capacity 0
Is Nil
*/