亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將結構切片附加到另一個

將結構切片附加到另一個

Go
白豬掌柜的 2023-05-08 15:30:35
我是 Golang 的新手,正在嘗試將一片結構的內容附加到另一個實例中。數據被追加,但在方法之外是不可見的。下面是代碼。package somepkgimport (    "fmt")type SomeStruct struct {    Name  string    Value float64}type SomeStructs struct {    StructInsts []SomeStruct}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)}然后在主包中初始化結構并調用 AddAllStructs 方法。package mainimport (  "hello_world/somepkg"  "fmt")func main() {    var someStructs = somepkg.SomeStructs{      []somepkg.SomeStruct{        {Name: "a", Value: 1.0},        {Name: "b", Value: 2.0},      },    }    var otherStructs = somepkg.SomeStructs{      []somepkg.SomeStruct{        {Name: "c", Value: 3.0},        {Name: "d", Value: 4.0},      },    }    fmt.Println("original::: ", someStructs)    fmt.Println("another::: ", otherStructs)    someStructs.AddAllStructs(otherStructs)    fmt.Println("After append in main::: ", someStructs)}上面的程序輸出如下:original:::  {[{a 1} {b 2}]}another:::  {[{c 3} {d 4}]}After append in method:::  [{a 1} {b 2} {c 3} {d 4}]After append in main:::  {[{a 1} {b 2}]}我試圖了解我在這里遺漏了什么,因為數據在方法中是可見的。感謝對此的任何幫助。
查看完整描述

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)

}

如果方法需要改變接收者,接收者必須是一個指針


查看完整回答
反對 回復 2023-05-08
?
拉丁的傳說

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]

}


查看完整回答
反對 回復 2023-05-08
?
紅顏莎娜

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


查看完整回答
反對 回復 2023-05-08
  • 3 回答
  • 0 關注
  • 155 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號