![](/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.