Go 包含结构的嵌入切片的结构
我有这个密码Go 包含结构的嵌入切片的结构,go,struct,constructor,Go,Struct,Constructor,我有这个密码 package main import ( "fmt" ) type foo struct { a int b bool } type foos []foo type bar struct { foos } func newBar() *bar { b := &bar{ foos: make([]foo, 3, 3), } for _, foo := range b.foos {
package main
import (
"fmt"
)
type foo struct {
a int
b bool
}
type foos []foo
type bar struct {
foos
}
func newBar() *bar {
b := &bar{
foos: make([]foo, 3, 3),
}
for _, foo := range b.foos {
// didn't set b to true
foo.b = true
}
return b
}
func main() {
b := newBar()
fmt.Println(b)
// set b to true
b.foos[0].b = true
fmt.Println(b)
}
如您所见,我想使用构造函数
newBar()
初始化bar
,但我希望嵌入类型foo.b使用非零值初始化,因此我使用for range语句初始化,但它没有按预期工作,foo.b
仍然为false,所有这些都是错误的。作为使用此代码的主函数中的比较b.foos[0]。b=true
。那么我的代码出了什么问题呢?天哪,我在发布这个问题后才意识到这一点,因为变量slot
是for loop
的本地变量。因此,解决方案是:
for i, _ := range b.foos {
// now b is set to true
b.foos[i].b = true
}
对在uz的
情况下,foo:=范围b.foos{
,b.foos
中的每个项目都会被复制到foo
,因此更改foo
不会反映在b.foos
中。您在回答中建议的解决方案通过引用原始实例来修复它,而不进行复制。但是,如果b.foos
是指向foo
的一段指针([]*foo
),指针将被复制,但不是原始值,因此u的,foo:=range b.foos{
,如果您首先分配了每个项,则会按预期工作。