将切片结构追加到另一个

时间:2018-11-09 04:15:14

标签: go struct slice

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

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

3 个答案:

答案 0 :(得分: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)
}
  

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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

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

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 park运行代码: https://play.golang.org/p/_vxx7Tp4dfN