Slices
Slices are like arrays but have a more dynamic nature and can grow and shrink over time.
Slices don't actually hold their own data, a slice always refers to data somewhere in some array, known as reference data types.
Array:
INDEX: 0 1 2 3 4 5 6 7 8 9
VALUES: 463 234 757 123 645 434 345 908 456 825
Slice:
INDEX: 0 1 2 3 4
VALUES: 757 123 645 434 345
Changing a values in the underlying array will be reflected in the slice and vise versa.
Initialize slice
To declare a slice we use the same syntax as defining an array but without specifying the number of elements.
An empty slice is initialized and contains nil, remember they don't hold there own data they hold memory address that point to data somewhere else in memory.
Populating slice
Just like when working with arrays, you can define initial values:
package main
import "fmt"
func main() {
mySlice := []int{10, 20, 30, 40, 50}
fmt.Println(mySlice)
}
Accessing slice
Like arrays, you can access specific elements:
package main
import "fmt"
func main() {
mySlice := []int{10, 20, 30, 40, 50}
fmt.Println(mySlice[3])
}
Modify slice
Likewise, you can modify specific elements:
package main
import "fmt"
func main() {
mySlice := []int{10, 20, 30, 40, 50}
fmt.Println(mySlice[3])
mySlice[3] = 42
fmt.Println(mySlice[3])
}
Copy slice
Unlike with arrays when you make a copy fo a slice, the data change in one will be reflecting in the other because the elements are pointers.
package main
import (
"fmt"
)
func main() {
mySlice := []int{10, 20, 30, 40, 50}
myNumbers := mySlice
mySlice[3] = 42
fmt.Println(mySlice)
fmt.Println(myNumbers)
}
Output:
Append to slice
Unlike with an array, slices have an append function:
package main
import "fmt"
func main() {
mySlice := []int{10, 20, 30, 40, 50}
mySlice = append(mySlice, 60, 70, 80, 90)
fmt.Println(mySlice)
}
Output:
Deleting from slice
Removing elements, need to number the start index and the end index, up to and not including (unless it's the last element):