gpt4 book ai didi

arrays - 声明数组大小是否明确确定按值传递还是按引用传递?

转载 作者:行者123 更新时间:2023-12-01 22:40:04 25 4
gpt4 key购买 nike

以数组副本不改变其父数组为例:

    a1 := [5]string{"English", "Japanese", "Spanish", "French", "Hindi"}
a2 := a1
fmt.Println("a1 = ", a1) //[English Japanese Spanish French Hindi]
fmt.Println("a2 = ", a2) //[English Japanese Spanish French Hindi]
a2[1] = "German"
fmt.Println("now a2 = ", a2) // [English German Spanish French Hindi]
fmt.Println("and a1 = ", a1) // [English Japanese Spanish French Hindi]
毫不奇怪,a2 是副本,而不是引用。更改副本不应该更改另一个副本,它们保存在不同的地址。
现在看看如果我们不向 a1 声明大小会发生什么:
    a1 := []string{"English", "Japanese", "Spanish", "French", "Hindi"} // <--difference here
a2 := a1
fmt.Println("a1 = ", a1) //[English Japanese Spanish French Hindi]
fmt.Println("a2 = ", a2) //[English Japanese Spanish French Hindi]
a2[1] = "German"
fmt.Println("now a2 = ", a2) // [English German Spanish French Hindi]
fmt.Println("and a1 = ", a1) // [English German Spanish French Hindi]
当 a2 改变时两者都改变​​?!所以,如果你没有为数组声明一个大小,然后将它分配给某个东西,突然它是一个引用?为什么 a2 := a1 的行为会完全不同,具体取决于另一个变量的声明方式?我很困惑哈哈。

最佳答案

我强烈建议阅读 Go 博客文章 Arrays, slices and strings - 然后再读一遍 - 它包含许多其他微妙的副作用。
它将显示幕后发生的事情以及 slice 类型的表示方式:

sliceHeader{
Length: 0,
Capacity: 0,
ZerothElement: nil, // points to a fixed size array
}
因此变异操作如何影响多个 slice 值。
最后的报价:

Arrays have their place—they are a good representation of atransformation matrix for instance—but their most common purpose in Gois to hold storage for a slice.

关于arrays - 声明数组大小是否明确确定按值传递还是按引用传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62972092/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com