当向切片中添加元素时出现混淆。

huangapple go评论78阅读模式
英文:

Confusion when appending to slice

问题

第一个例子中,当向y追加元素时,x也会发生变化,这是因为切片y和切片x共享相同的底层数组。切片是对底层数组的引用,所以对切片的修改会影响到底层数组。

第二个例子中,当向y追加元素时,x不会发生变化。这是因为在追加元素之前,y的容量已经达到了4,超过了原始切片x的容量。此时,append函数会创建一个新的底层数组来存储y的元素,而不是修改原始的底层数组。

容量的影响:当切片的容量足够容纳新的元素时,追加操作会修改原始的底层数组。但当切片的容量不足时,追加操作会创建一个新的底层数组,并将原始切片的元素复制到新的底层数组中。

如果将容量改为5,那么第三个例子中的x和y的输出将会是:

x: [1 2 30 40]
y: [1 2 30 40 50]

在这种情况下,x确实包含了50,因为切片y的容量足够容纳新的元素,所以追加操作会修改原始的底层数组。

英文:

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?

答案1

得分: 2

在第一种情况下,y具有与x相同的基础数组,当你向y添加元素并且所有元素都适合该数组时,x也会受到影响。

在第二种情况下,y最初具有与x相同的基础数组,但当你尝试添加新值时,基础数组不够大,因此会分配一个新的数组,而x不受影响。

在第三种情况下,与第一种情况类似-当你向y添加元素时,x也会受到影响。当你打印x的内容时,会考虑x的长度,因此只打印前4个值(即使x的容量为5,它的长度为4)。

英文:

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

huangapple
  • 本文由 发表于 2022年8月4日 19:06:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/73234820.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定