Go Slices
A slice feels a lot like an array, with more power and flexibility.
It also keeps many values of one type in a single variable. The big difference is size: a slice can get longer or shorter whenever you need it to, while an array cannot.
You have a few options for creating one:
- Write the values directly, in the
[]datatype{values}form - Cut a slice out of an existing array
- Call the
make()function
Create a Slice With []datatype{values}
The most direct way to declare a slice is to list its values inside curly braces, as the syntax shows.
Two built-in functions tell you about any slice. len() gives its length, meaning how many elements it currently holds. cap() gives its capacity, meaning how many elements it has room for.
Example
Both slices below are written in this form. The first has no values, so its length and capacity are 0; the second holds four values, so both are 4:
Output: Go program and captured output
package main
import ("fmt")
func main() {
myslice1 := []int{}
fmt.Println(len(myslice1))
fmt.Println(cap(myslice1))
fmt.Println(myslice1)
myslice2 := []string{"Go", "Slices", "Are", "Powerful"}
fmt.Println(len(myslice2))
fmt.Println(cap(myslice2))
fmt.Println(myslice2)
}
Syntax
slice_name := []datatype{values}
Create a Slice From an Array
Another option is to take part of an array, by giving a start and end position in square brackets.
Example
arr1[2:4] covers index 2 up to, but not including, index 4. The capacity is 4 because four elements remain in the array from index 2 onward:
Output: Go program and captured output
package main
import ("fmt")
func main() {
arr1 := [6]int{10, 11, 12, 13, 14, 15}
myslice := arr1[2:4]
fmt.Printf("myslice = %v\n", myslice)
fmt.Printf("length = %d\n", len(myslice))
fmt.Printf("capacity = %d\n", cap(myslice))
}
Syntax
var myarray = [length]datatype{values} // An array
myslice := myarray[start:end] // A slice made from the array
Create a Slice With The make() Function
Calling make() is a third way to get a slice, and it lets you choose the length and capacity.
Note: capacity is optional. Leave it out and it takes the same value as length.
Example
myslice1 gets a length of 5 and a capacity of 10. myslice2 gives no capacity, so it ends up with 5 for both:
Output: Go program and captured output
package main
import ("fmt")
func main() {
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))
// with omitted capacity
myslice2 := make([]int, 5)
fmt.Printf("myslice2 = %v\n", myslice2)
fmt.Printf("length = %d\n", len(myslice2))
fmt.Printf("capacity = %d\n", cap(myslice2))
}
Syntax
slice_name := make([]type, length, capacity)