Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/elixir/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Go 分配一个引用类型的变量;切片;对于另一个变量,为什么不';它们不是同时变化的吗?_Go_Reference Type - Fatal编程技术网

Go 分配一个引用类型的变量;切片;对于另一个变量,为什么不';它们不是同时变化的吗?

Go 分配一个引用类型的变量;切片;对于另一个变量,为什么不';它们不是同时变化的吗?,go,reference-type,Go,Reference Type,此代码段将输出false。为什么? 下面是一些其他实验: anotherSlice := theSlice anotherSlice = append(anotherSlice, newEle) fmt.Println(len(anotherSlice) == len(theSlice)) 输出如下所示: package main import "fmt" func main() { theSlice := []int{3,3,2,5,12,43} anotherSlice

此代码段将输出
false
。为什么?

下面是一些其他实验:

anotherSlice := theSlice
anotherSlice = append(anotherSlice, newEle)
fmt.Println(len(anotherSlice) == len(theSlice))
输出如下所示:

package main

import "fmt"

func main() {
    theSlice := []int{3,3,2,5,12,43}
    anotherSlice := theSlice
    fmt.Println(anotherSlice[3], theSlice[3])
    anotherSlice[3] = anotherSlice[3]+2
    fmt.Println(anotherSlice[3], theSlice[3])
    anotherSlice = append(anotherSlice[:3], anotherSlice[4:]...)
    fmt.Println(len(anotherSlice),len(theSlice))
}

每当追加的切片
另一个切片
没有新元素的容量时,
append
函数就会创建新切片并返回它。从那时起,片
另一个片
和片是不同的-它们由单独的数组支持

以较短的长度重新扫描另一个切片[:3]不会影响切片的原始容量

以下一行:

5 5
7 7
5 6

Program exited.
剪切第四个(索引3)元素。因为
anotherSlice[:3]
有能力保存
anotherSlice[4:][/code>的所有元素,所以不会发生新的分配,因此两个片都会被修改

anotherSlice = append(anotherSlice[:3], anotherSlice[4:]...)


为什么一个片的长度不随另一个片的长度变化而变化,答案与可能被复制和/或修改的底层存储无关

anotherSlice = append(anotherSlice[:3], anotherSlice[4:]...)
在围棋中,记住什么是切片是很重要的。它是一个包含长度字段、容量字段和数组指针的结构。一些操作 更改“长度”字段。有些更改了容量字段。有些更改存储在基础数组中的数据


如果一个人不理解一个切片是如何在语言中实现的,那么就会有各种各样的混乱、错误和浪费的机会。一旦人们熟悉了切片的实现方式,它们就非常易于使用,而且编译器了解切片的结构,就可以编写一些非常优雅且易于阅读的代码。

我尝试了其他方法来缩短长度,该过程会在文章中更新。这是因为在缩小后,另一个片的容量也缩小到了5吗?