On Thu, Jan 4, 2018 at 10:08 AM, Frank Davidson <ffdavid...@gmail.com> wrote: > > I'm sure this has probably been answered before, but I have a question about > when a slice's underlying array is copied? In this code: > > https://play.golang.org/p/TnMFo-rYKzq > > package main > > import ( > "fmt" > ) > > func main() { > > out := []byte{1, 2, 3, 4} > fmt.Println(out) > proc(out) > fmt.Println(out) > proc2(out) > fmt.Println(out) > > } > > func proc(p []byte) { > p = []byte{5,6,7,8} > } > > func proc2(p []byte) { > p[0] = 5 > p[1] = 6 > p[2] = 7 > p[3] = 8 > } > > > The output is: > > [1 2 3 4] > [1 2 3 4] > > [5 6 7 8] > > > I assume that in proc the slice's underlying array is being copied as well? > Hence p is referring to a new array within the function and, thus, the > underlying original array is not modified, even though it's capacity > wouldn't have to change? But in proc2 there is no copy of the underlying > array made, hence the original array is modified? What is the rule for when > the underlying array is also copied and when it is not?
In the way that I use the word "copied", the underlying array of a slice is never copied (except if you do it yourself, or via the copy or append functions). I recommend that you read https://golang.org/blog/slices. Ian -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.