Why appending on slice modified another slice?

Issue

package main

import "fmt"

func main() {
    src := []int{0, 1, 2, 3, 4, 5, 6}
    a := src[:3]
    b := src[3:]
    a = append(a, 9)

    fmt.Println(a, b)
}

output:

[0 1 2 9] [9 4 5 6]

Did append modified the underlay array as []int{0, 1, 2, 9, 4, 5, 6}?
Slice a was copied as a new slice with a new underlay array with value [0, 1, 2, 9] and slice b still pointing to the old array that was modified.

Thanks for any hints, much appreciated

Solution

  • Slice a was copied as a new slice with a new underlay array with value [0, 1, 2, 9] and slice b still pointing to the old array that was modified.
  • a := src[:3] created a slice (a pointer to the src head, length=3, capacity=7)
  • b := src[3:] created a slice(a pointer to the src[3],length=4, capacity=4)
  • a and b shares the same memory created by src
  • a = append(a, 9),when appending to the same slice, as long as it does not exceed cap, it is the same array that is modified
  • Did append modified the underlay array as []int{0, 1, 2, 9, 4, 5, 6}

YES

If the append exceed the cap of a, new array will be allocated and data will be copied the the new array

try this out:

package main

import "fmt"

func main() {
    src := []int{0, 1, 2, 3, 4, 5, 6}
    a := src[:3]
    b := src[3:]
    a = append(a, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9)

    fmt.Println(a, b)
}

Output:

[0 1 2 9 9 9 9 9 9 9 9 9 9] [3 4 5 6]

Answered By – zhlicen

Answer Checked By – David Goodson (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.