英文:
Why slice append element not update referenced element?
问题
这是我对Go语言中切片的了解:
- 当元素数量和容量宽度相同时(len(fruits) == cap(fruits)),通过append()添加的新元素会创建一个新的引用。
- 当元素数量小于容量时(len(fruits) < cap(fruits)),新元素会被放置在容量范围内,导致所有其他具有相同引用的切片元素的值发生变化。
你的代码中有以下部分:
package main
import (
"fmt"
)
func main() {
//声明切片
var fruits = []string{"banana", "mango", "tomato"}
//使用两个索引创建切片
var newFruits = fruits[1:2]
//向fruits切片添加元素
fruits = append(fruits, "papaya")
//向newFruits切片添加元素
newFruits = append(newFruits, "dragon")
fmt.Println(cap(fruits)) //2
fmt.Println(cap(newFruits)) //6
fmt.Println(newFruits) //[mango dragon]
fmt.Println(fruits) //[banana mango tomato papaya]
}
为什么fruits的值不是[banana mango dragon papaya]呢?
英文:
This rule is what I know about slice in Go
- When the number of elements and the width of the capacity are the same (len(fruits) == cap(fruits)), the new element resulting from append() is the new reference.
- When the number of elements is less than the capacity (len(fruits) < cap(fruits)), the new element is placed into the capacity range, causing all other slice elements with the same reference to change in value.
I have code like this
package main
import (
"fmt"
)
func main() {
//declare slice
var fruits = []string{"banana", "mango", "tomato"}
//using two index technique to make slice
var newFruits = fruits[1:2]
//append element to fruits slice
fruits = append(fruits, "papaya")
//append element to newFruits slice
newFruits = append(newFruits, "dragon")
fmt.Println(cap(fruits)) //2
fmt.Println(cap(newFruits)) //6
fmt.Println(newFruits) //[mango dragon]
fmt.Println(fruits) //[banana mango tomato papaya]
}
why the value of fruits is not [banana mango dragon papaya]?
答案1
得分: 0
这是代码的工作原理:
在将 papaya
添加到 fruits
之前,
fruits = {"banana", "mango", "tomato";}
newFruits
指向与 fruits
相同的数组,但从 mango
开始。
当你将 papaya
添加到 fruits
时,会创建一个容量为 6 的新数组,因为 fruits
的容量为 3。fruits
现在指向这个新数组,其中有 4 个值:
fruits = {"banana", "mango", "tomato", "papaya"};
newFruits
仍然指向旧的 fruits
数组,并包含 2 个元素。
英文:
Here's how the code works:
Just before appending papaya
to fruits
,
fruits = {"banana", "mango", "tomato"}
and newFruits
points to the same array as fruits
but starting from mango
.
When you append papaya
to fruits
, a new array is created with capacity=6, because the capacity of fruits
is 3. fruits
now points to this new array, with 4 values:
fruits = {"banana", "mango", "tomato", "papaya"}
newFruits
still points to the old fruits
array, and contains 2 elements.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论