Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Slice of a slice

We can take a slice of a slice. It is just another, most likely smaller, window on the same array in the background.

package main

import (
	"fmt"
)

func main() {
	var dwarfs = []string{"Doc", "Grumpy", "Happy", "Sleepy", "Bashful", "Sneezy", "Dopey"}

	a := dwarfs[:]
	b := dwarfs[2:4]

	fmt.Println(dwarfs)
	fmt.Println(a)
	fmt.Println(b)

	dwarfs[2] = "Snowwhite"
	fmt.Println()
	fmt.Println(dwarfs)
	fmt.Println(a)
	fmt.Println(b)
}
[Doc Grumpy Happy Sleepy Bashful Sneezy Dopey]
[Doc Grumpy Happy Sleepy Bashful Sneezy Dopey]
[Happy Sleepy]

[Doc Grumpy Snowwhite Sleepy Bashful Sneezy Dopey]
[Doc Grumpy Snowwhite Sleepy Bashful Sneezy Dopey]
[Snowwhite Sleepy]
  • This would work on arrays as well: Slices of an array