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?

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

Reply via email to