Slices
Slices are similar to arrays, but offer more powerful ways of dealing with data.
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)
}Last updated