Slices
Slices are similar to arrays, but offer more powerful ways of dealing with data.
Last updated
Slices are similar to arrays, but offer more powerful ways of dealing with data.
Last updated
The type of a slice is determined only by the elements it contains, and is independent of the the number of elements in the slice. Slices also support various built-in methods in golang including make
, copy
, append
etc. We will explore some of these methods below.
Slices are similar to C++ vectors in that they can grow and shrink dynamically. We can initialize a string
slice below with 4 initial values.
package main
import "fmt"
func main() {
cars := make([]string, 4)
fmt.Println("empty slice:", cars)
cars[0] = "tesla"
cars[1] = "bmw"
cars[2] = "honda"
// print out all the values currently in cars
fmt.Println(cars)
fmt.Printf("Third car: %s", s[2])
// the len method works on slices too
fmt.Println("len:", len(s))
// add new items to the cars slice
// Note: we need to reassign cars to the value of append
cars = append(cars, "rivian")
cars = append(s, "toyota", "buick")
fmt.Println(cars)
// make a copy of the car slice
cars_copy := make([]string, len(cars))
copy(cars_copy, cars)
fmt.Println(cars_copy)
}
Slices also support "slicing" using a colon symbol. "slicing" here refers to getting only parts of a slice data structure. For example,
package main
import "fmt"
func main() {
authors := []string {"Hurston", "Artwood", "Didion", "Le Guin", "Morrison", "Walker"}
// "slicing" takes the format slice[low:high].
// For example, this gets a slice of the elements
// authors[2], authors[3], and authors[4].
some_authors := s[2:5]
fmt.Println("some authors:", some_authors)
// slice up to (but excluding) authors[5].
famous_authors = authors[:5]
fmt.Println("These authors are famous: ", famous_authors)
// slice from 3 (inclusive) to the end
contemporary_authors = authors[3:]
}