繁体   English   中英

将切片结构追加到另一个

[英]Append slice of struct into another

我是Golang的新手,正在尝试将结构片段的内容附加到另一个实例中。 数据被追加,但在方法外部不可见。 下面是代码。

package somepkg

import (
    "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 main

import (
  "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}]}

我试图了解我在这里缺少什么,因为数据在方法中可见。 感谢对此的任何帮助。

-Anoop

使用指针接收器:

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)
}

如果该方法需要更改接收方,则接收方必须是指针

您必须返回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]
}

通过使用指针接收器而不是值接收器,可以轻松解决此问题。

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)
} 

请记住,如果您看到切片内部,则它是一个包含指向数据结构的指针的结构。

因此,主要的切片不知道新添加的切片和已打印的同一切片的容量。

其次,您不必返回附加切片的结果。 这里的指针接收器是为拯救而来的,因为值接收器无法更改原始值。

在操场上运行代码: https : //play.golang.org/p/_vxx7Tp4dfN

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM