Can someone explain why in the first example if appending to y changes also x but in the second example it doesnt?
x := make([]int, 0, 4)
x = append(x, 1, 2, 3, 4) //len(x)=4 and cap(x)=4
y := x[:2] //Len(y)=2 and cap(y)=4
y = append(y, 30, 40)
fmt.Println("x:", x)
fmt.Println("y:", y)
//x: [1 2 30 40]
//y: [1 2 30 40]
x := make([]int, 0, 4)
x = append(x, 1, 2, 3, 4) //len(x)=4 and cap(x)=4
y := x[:2] //Len(y)=2 and cap(y)=4
y = append(y, 30, 40,50)
fmt.Println("x:", x)
fmt.Println("y:", y)
//x: [1 2 3 4]
//y: [1 2 30 40 50]
And how is this affected by the capacity? For example if I change the capacity to 5
x := make([]int, 0, 5)
x = append(x, 1, 2, 3, 4)
y := x[:2]
y = append(y, 30, 40, 50)
fmt.Println("x:", x)
fmt.Println("y:", y)
//x: [1 2 30 40]
//y: [1 2 30 40 50]
then it seems to work but then I would assume that x also contains 50?
CodePudding user response:
In the first case y
has the same underlying array as x
and as you append to y
and everything fits into that array x
is also affected.
In the second case y
has the same underlying array as x
as first, but when you try to append new values the underlying array is not enough so a new one is allocated and x
is unaffacted.
In the third case it's similar to the first one - when you append things to y
it affects x as well. When you print the contents of x
the len
of x
is took into consideration so only the first 4 values are printed (x has a length of 4, even though it has the capacity of 5).