英文:
missing type in composite literal in nested struct
问题
我有以下匿名结构体:
func wrapHal(selfHref string) interface{} {
return struct {
_links struct {
self struct {
href string
}
}
}{
_links: struct {
self struct {
href string
}
}{
self: struct {
href string
}{
href: selfHref,
},
},
}
}
然而,在"this line"这一行,我得到了错误信息missing type in composite literal
。
如何修复它?在Go中是否可以初始化一个匿名嵌套结构体?
英文:
I have the following anonymous struct:
func wrapHal(selfHref string) interface{} {
return struct {
_links struct {
self struct {
href string
}
}
}{
_links: {self: {href: selfHref}}, # this line
}
}
However, in "this line, " I get the error missing type in composite literal
How to fix it? It is possible to initiate a anonymous nested struct in Go?
答案1
得分: 2
要初始化一个匿名结构体,你需要先声明类型。你已经声明了根匿名结构体,但是对于每个嵌套的匿名结构体,你需要再次声明类型:
func wrapHal(selfHref string) interface{} {
return struct {
_links struct {
self struct {
href string
}
}
}{
_links: struct {
self struct {
href string
}
}{
self: struct {
href string
}{
href: "",
},
},
}
}
英文:
To initialize an anonymous struct, you have to declare the type. You declared the root anonymous struct, but you need to do again for each nested anonymous struct:
func wrapHal(selfHref string) interface{} {
return struct {
_links struct {
self struct {
href string
}
}
}{
_links: struct {
self struct {
href string
}
}{
self: struct {
href string
}{
href: "",
},
},
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论