2017-07-28 145 views
-1
type important struct { 
client  string     `json:"client"` 
Response Summary  `json:"response"` 

}如何初始化golang中的嵌套结构?

type Summary struct { 
Name  string   `json:"name"` 
Metadata Clientdata  `json:"metadata"` 
} 

type Clientdata struct { 
Income string   `json:"income"` 
} 


v := &important{ client: "xyz", Response: Summary[{ 
      Name: "test", 
      Metadata: Clientdata { "404040"}, 
     } 
    }] 

//错误:无法使用摘要{名称: “测试”,元数据:Clientdata { “404040”},}(类型总结)如式[]总结更多...

我在做什么错在这里?

+0

自己动手https://github.com/golang/go/wiki/CodeReviewComments#gofmt –

回答

1

简而言之,你略微去掉了切片文字的语法。你的错误是相当合乎逻辑的,但可惜它不起作用。

下面是一个固定的版本:

v := &important{ client: "xyz", Response: []Summary{ 
     { 
      Name: "test", 
      Metadata: Clientdata { "404040"}, 
     }, 
    }, 
} 

切片字面定义,像这样:

[]type{ items... } 
0

目前还不清楚你如何想接近它,因为你的反应意味着结构[] VmSummary信息,但你正在喂它[]摘要。

此外,请检查https://blog.golang.org/go-slices-usage-and-internals有关数组的初始化。

这样的事情?

type important struct { 
    client string `json:"client"` 
    Response []Summary `json:"response"` 
} 

type Summary struct { 
    Name  string  `json:"name"` 
    Metadata Clientdata `json:"metadata"` 
} 

type Clientdata struct { 
    Income string `json:"income"` 
} 

func main() { 
    v := &important{ 
     client: "xyz", 
     Response: []Summary{ 
      { 
       Name:  "test", 
       Metadata: Clientdata{"404040"}, 
      }, 
     }, 
    } 
}