3 回答

TA貢獻1942條經驗 獲得超3個贊
使用指針接收器:
func (ss *SomeStructs) AddAllStructs(otherstructs SomeStructs) {
if ss.StructInsts == nil {
ss.StructInsts = make([]SomeStruct, 0)
}
for _, structInst := range otherstructs.StructInsts {
ss.StructInsts = append(ss.StructInsts, structInst)
}
fmt.Println("After append in method::: ", ss.StructInsts)
}
如果方法需要改變接收者,接收者必須是一個指針

TA貢獻1789條經驗 獲得超8個贊
您必須返回以下結果append:
package main
import (
"fmt"
)
func main() {
// Wrong
var x []int
_ = append(x, 1)
_ = append(x, 2)
fmt.Println(x) // Prints []
// Write
var y []int
y = append(y, 1)
y = append(y, 2)
fmt.Println(y) // Prints [1 2]
}

TA貢獻1842條經驗 獲得超13個贊
您可以通過使用指針接收器而不是值接收器輕松解決此問題。
func (ss *SomeStructs) AddAllStructs(otherstructs SomeStructs) {
if ss.StructInsts == nil {
ss.StructInsts = make([]SomeStruct, 0)
}
for _, structInst := range otherstructs.StructInsts {
ss.StructInsts = append(ss.StructInsts, structInst)
}
fmt.Println("After append in method::: ", ss.StructInsts)
}
記住在 go 中,如果你看到一個切片內部結構,它是一個包含指向數據結構指針的結構。
所以主要的切片不知道新附加切片的容量并且已經打印了相同的切片。
其次,您不必返回附加切片的結果。這里指針接收者來救援,因為值接收者不能改變原始值。
在 go playground 運行代碼: https ://play.golang.org/p/_vxx7Tp4dfN
- 3 回答
- 0 關注
- 155 瀏覽
添加回答
舉報