我是 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}]}
我试图了解我在这里遗漏了什么,因为数据在方法中是可见的。感谢对此的任何帮助。
手掌心
拉丁的传说
红颜莎娜
相关分类