英文:
How initialize nested complex structure
问题
我有以下嵌套结构:
type PDescr struct {
Name string
Dir int32
}
type DDescr struct {
MPins map[string]*PDescr
}
type P_DB struct {
MId int32
MDevs map[string]*DDescr
}
type S_DB struct {
TId int32
}
type Main_DB struct {
FId int32
Path string
PDb *P_DB
SDb *S_DB
}
我的主要结构是 Main_DB。
在 Go 语言中,我开始生成结构初始化,但不知道如何做:
我最新的结构初始化版本如下,但无法编译:
book = &pb.Main_DB{
FId: 666,
Path: "my_path",
PDb: &pb.P_DB{
MId: 5,
MDevs: []string*DDescr{
MPins: map[string]*PDescr{
Name: "aa",
Dir: 7,
},
},
},
SDb: &pb.S_DB{
TId: 777,
},
}
我在 MDevs map[string]*DDescr
的初始化上遇到了困难。我不知道如何正确传递值。
有什么想法吗?
谢谢!
英文:
I have following nested structures:
type PDescr struct {
Name string
Dir int32
}
type DDescr struct {
MPins map[string]*PDescr
type P_DB struct {
MId int32
MDevs map[string]*DDescr
}
type S_DB struct {
TId int32
}
type Main_DB struct {
FId int32
Path string
PDb *P_DB
SDb *S_DB
}
My main structure is Main_DB.
In Go I started generate structure initialization and can't understand how to do this:
My latest version of sach initialization is the following which is not compiled:
book=&pb.Main_DB{
FId: 666,
Path: "my_path",
PDb: &pb.P_DB{
MId: 5,
MDevs: []string*DDescr {
MPins: map[string]*PDescr {
Name: "aa",
Dir: 7,
},
},
},
SDb: &pb.S_DB{
TId: 777,
},
}
I'm stuck with MDevs map[string]*DDescr
initialization. I don't know how correct propogate values.
Any ideas?
Thanks!
答案1
得分: 1
你提供的代码中有几个语法错误,不确定是不是因为你试图提供一个更简短的版本作为示例。
此外,你忘记为嵌套的映射初始化key
。
例如:
MDevs: map[string]*DDescr
所以MDevs
是一个具有string
键和*DDescr
值的map
,可以像这样进行初始化:
MDevs: map[string]*DDescr{
"first": &DDescr{ /* 这个结构体的字段 */ },
}
我在这里尝试重新生成了你的示例,它可以正常工作:https://play.golang.org/p/Zn8u0f92Xn
英文:
There are couple of syntax errors in code you provided, not sure if it's because you tried to give shorter version to give an example.
Also, you are missing to initialize key
for nested maps.
> Example : MDevs: map[string]*DDescr
>
> So MDevs
is map
with
> string
keys and *DDescr
values, which can be initialized like
>
> MDevs: map[string]*DDescr{
> "first": &DDescr{ fields from this struct
}
> }
I tried to re-produce your example here, which is working fine: https://play.golang.org/p/Zn8u0f92Xn
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论