![](/img/trans.png)
[英]For a Go slice, what is the difference between the slice and a full reslice of the slice?
[英]What is a difference between these two “slice copy” approaches in Go
那么,为什么它们(下面的 No.1 和 No.2)不同?
type T1 struct {
local []string
}
func (t *T1) Assign(param ...string) {
t.local = nil
t.local = append(t.local, param...) // No.1 <<<
t.local = param[:] // No.2 <<<
}
它们肯定是不同的:No.2 相当“浅”。
当更改t.local[i]
时,如果使用 2 号,她会将原始字符串乱码。
您的“No.1”方法附加到一个nil
切片,它保证如果提供的参数超过零,则将分配一个新的支持数组。
您的“No.2”方法不会创建新切片,它只是切片参数。
如果通过传递现有切片调用Assign()
,则第二种方法将存储该切片,如果其元素被修改,它将反映在存储的切片中。
让我们稍微修改一下您的示例以对其进行测试:
type T1 struct {
local []string
}
func (t *T1) Assign1(param ...string) {
t.local = nil
t.local = append(t.local, param...) // No.1 <<<
}
func (t *T1) Assign2(param ...string) {
t.local = nil
t.local = param[:] // No.2 <<<
}
测试它:
t1 := &T1{}
s := []string{"a", "b", "c"}
t1.Assign1(s...)
fmt.Println(t1.local)
s[0] = "x"
fmt.Println(t1.local)
s = []string{"a", "b", "c"}
t1.Assign2(s...)
fmt.Println(t1.local)
s[0] = "x"
fmt.Println(t1.local)
Output(在Go Playground上尝试):
[a b c]
[a b c]
[a b c]
[x b c]
如您所见,当使用Assing1()
时, local
切片不受修改传递的切片的影响。
使用Assing2()
时, local
切片的元素会反映原始切片中所做的更改。
请阅读相关博文:
那么,为什么它们(下面的 No.1 和 No.2)不同?
type T1 struct {
local []string
}
func (t *T1) Assign(param ...string) {
t.local = nil
t.local = append(t.local, param...) // No.1 <<<
t.local = param[:] // No.2 <<<
}
它们肯定是不同的:No.2 相当“浅”。
当更改t.local[i]
时,如果使用 2 号,她会将原始字符串乱码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.