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 Pointer and copy slice

  • copy

  • Assigning a slices assigns the reference to the slice, to the same place in memory.

  • However if we then change one of the variables (e.g. enlarge it), it might be moved to another array and then the two get separated.

  • If we assign a pointer to the slices, that pointer goes to the "head of the slice" which is moved when we move the slice.

package main

import (
	"fmt"
)

func main() {
	a := []string{"Foo", "Bar"}
	b := a
	c := &a
	d := make([]string, len(a))
	copy(d, a)
	fmt.Println(a)
	fmt.Println(b)
	fmt.Println(c)
	fmt.Println(d)
	fmt.Println()

	a[0] = "Zorg"
	fmt.Println(a)
	fmt.Println(b)
	fmt.Println(c)
	fmt.Println(d)
	fmt.Println()

	a = append(a, "Other")
	fmt.Println(a)
	fmt.Println(b)
	fmt.Println(c)
	fmt.Println(d)

}
[Foo Bar]
[Foo Bar]
&[Foo Bar]
[Foo Bar]

[Zorg Bar]
[Zorg Bar]
&[Zorg Bar]
[Foo Bar]

[Zorg Bar Other]
[Zorg Bar]
&[Zorg Bar Other]
[Foo Bar]