【问题标题】:How to initialise the nested structure in go? [duplicate]go中如何初始化嵌套结构? [复制]
【发布时间】:2017-08-04 13:30:49
【问题描述】:

我的结构是这样的

type A struct{
        B struct{
           C interface{} `json:"c"`
     }
}
type C struct{
        D  string  `json:"d"`
        E  string  `json:"e"`
}

这个struct的使用是这样的,

func someFunc(){
  var x A
  anotherFunc(&x)
}

func anotherFunc(obj interface{}){
// resp.Body has this {D: "123", E: "xyx"} 
 return json.NewDecoder(resp.Body).Decode(obj)
}

我必须为单元测试初始化​​它,我正在这样做,

x := &A{
        B: {
             C : map[string]interface{}{
                 D: 123,
                 E: xyx,
             },
        },
} 

但收到错误missing type in composite literal,我做错了什么?

【问题讨论】:

  • 我尝试了解释的方式,但它仍然无法正常工作,它显示cannot use struct {C interface} literal (type struct{C interface{}} as type struct{C interface{}}) *some weird error* in field value

标签: go struct nested


【解决方案1】:

问题在于B 是一个匿名的嵌入式结构。为了将结构文字定义为另一个结构的成员,您需要给出类型。最简单的做法是为您的匿名类型定义结构类型。

你可以通过做这个非常丑陋的事情来让它工作(假设 C 和 D 在某处定义):

x := &A{
        B: struct{C interface{}}{
             C : map[string]interface{}{
                 D: 123,
                 E: xyx,
             },
        },
} 

【讨论】:

  • 谢谢@captncraig,但它不起作用,我已经改进了这个问题,再看看它。
猜你喜欢
  • 2015-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多