Slice Assign


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.

examples/slice-assign/slice_assign.go
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)
}

examples/slice-assign/slice_assign.out
[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]