为什么切片追加元素不会更新引用的元素?

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

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 (
	&quot;fmt&quot;
)

func main() {
	//declare slice
	var fruits = []string{&quot;banana&quot;, &quot;mango&quot;, &quot;tomato&quot;}

	//using two index technique to make slice
	var newFruits = fruits[1:2]

	//append element to fruits slice
	fruits = append(fruits, &quot;papaya&quot;)
	
	//append element to newFruits slice
	newFruits = append(newFruits, &quot;dragon&quot;)

	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 = {&quot;banana&quot;, &quot;mango&quot;, &quot;tomato&quot;}

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 = {&quot;banana&quot;, &quot;mango&quot;, &quot;tomato&quot;, &quot;papaya&quot;}

newFruits still points to the old fruits array, and contains 2 elements.

huangapple
  • 本文由 发表于 2021年11月30日 14:14:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/70165088.html
匿名

发表评论

匿名网友

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

确定