For example:
package main
import "fmt"
type Test struct {
elems []string
}
func main() {
initial := Test{
elems: make([]string, 0),
}
initial.elems = append(initial.elems, "apple")
fmt.Println(initial.elems) // #1 [apple]
s := make([]Test, 0)
s = append(s, initial)
initial.elems = append(initial.elems, "bannana")
fmt.Println(initial.elems) // #2 [apple bannana]
fmt.Println(s[0].elems) // #3 [apple]
second := s[0]
second.elems = append(second.elems, "carrot")
fmt.Println(second.elems) // #4 [apple bannana]
}
I am looking for help understanding print statements #3 and #4. In #3 I expect [apple bannana]
and in #4 I am expecing [apple bannana carrot]
.
It is my understanding that the elems
field which is a slice is automatically passed by reference and therefore each append that I do in the above block of code should modify the underlying array. But, apparently that is not the case.
So, my question is: What happens to initial
when it gets inserted into a slice that makes this not work? Also, how would one write this code to get the expected result at print statement #4?