-2
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

davyzhang
  • 2,419
  • 3
  • 26
  • 34
  • Does `go vet` complain? – iuridiniz Feb 11 '22 at 01:59
  • 2
    See https://stackoverflow.com/q/17395261/12258482, https://stackoverflow.com/q/59596644/5728991, and many more –  Feb 11 '22 at 02:34
  • 2
    `append` does allocate new underlying array only if the old one has no sufficient capacity. Otherwise it assigns the value at the position instead. – rustyhu Feb 11 '22 at 02:47
  • 1
    Read this answer: [Concatenate two slices in Go](https://stackoverflow.com/questions/16248241/concatenate-two-slices-in-go/40036950#40036950). – icza Feb 11 '22 at 07:15

1 Answers1

0
  • 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]

zhlicen
  • 346
  • 1
  • 10