Go Slices

Slices are like references to arrays

A slice does not store any data, it just describes a section of an underlying array. Changing the elements of a slice modifies the corresponding elements of its underlying array. Other slices that share the same underlying array will see those changes.

package main

import "fmt"

func main() {
	names := [4]string{
		"John",
		"Paul",
		"George",
		"Ringo",
	}
	fmt.Println(names)  // [John Paul George Ringo]
	a := names[0:2]
	b := names[1:3]
	fmt.Println(a, b)  // [John Paul] [Paul George]
	b[0] = "XXX"
	fmt.Println(a, b)  // [John XXX] [XXX George]
	fmt.Println(names) // [John XXX George Ringo]
}

Notice Paul the 0 in names array ,the 0 in b slice the, the 1 in a slice changed in all of them

Slice literals

A slice literal is like an array literal without the length. This is an array literal:

And this creates the same array as above, then builds a slice that references it:

Example

Slice length and capacity

Creating a slice with make

Slices of slices

Appending to a slice

Range

Last updated

Was this helpful?