如何初始化嵌套的复杂结构?

huangapple go评论80阅读模式
英文:

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

huangapple
  • 本文由 发表于 2016年12月20日 22:28:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/41244629.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定