我正在尝试用程序创建一些API文档,我有这个:
type APIDoc struct {
Route string
ResolutionValue struct {
v string
}
}
然后我试着这样做:
json.NewEncoder(w).Encode(APIDoc.ResolutionValue{"foo"})
但它说
APIDoc.ResolutionValue未定义(类型APIDoc没有方法分辨率值(
所以我不得不这样做:
type ResolutionValue struct {
v string
}
type APIDoc struct {
Route string
ResolutionValue ResolutionValue
}
然后做:
json.NewEncoder(w).Encode(ResolutionValue{"foo"})
有点蹩脚,有没有办法以某种方式确保诚信?
从Go 1.11开始,不支持嵌套类型。
方案讨论
你的修改看起来好多了IMO.
编辑:也许与问题无关,但你可以使用类型嵌入来简化你的类型。但是,请注意,表示方式不同:
type Inner struct {
Whatever int
}
type ResolutionValue struct {
Val string
Inner
}
type ResolutionValue2 struct {
Val string
Inner Inner
}
func main() {
a, _ := json.Marshal(ResolutionValue{})
b, _ := json.Marshal(ResolutionValue2{})
fmt.Printf("%sn%s", a, b)
}
打印:
{"Val":"","Whatever":0}
{"Val":"","Inner":{"Whatever":0}}