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 Assign

  • It is an alias to the other slice, same place in memory

Unlike with arrays, when we assign a slice, we only assign the location of the slice in the memory. So if we change the content of one of the slices then the other one also sees the change.

package main

import (
	"fmt"
)

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

	fmt.Println(dwarfs)
	fmt.Println(theSeven)

	dwarfs[1] = "Snowwhite"

	fmt.Println(dwarfs)
	fmt.Println(theSeven)
}
[Doc Grumpy Happy Sleepy Bashful Sneezy Dopey]
[Doc Grumpy Happy Sleepy Bashful Sneezy Dopey]
[Doc Snowwhite Happy Sleepy Bashful Sneezy Dopey]
[Doc Snowwhite Happy Sleepy Bashful Sneezy Dopey]