我正在嘗試以編程方式創建一些 API 文檔,我有這個:type APIDoc struct { Route string ResolutionValue struct { v string }}然后我嘗試這樣做: json.NewEncoder(w).Encode(APIDoc.ResolutionValue{"foo"})但它說APIDoc.ResolutionValue 未定義(類型 APIDoc 沒有方法 ResolutionValue)所以我求助于這樣做:type ResolutionValue struct { v string}type APIDoc struct { Route string ResolutionValue ResolutionValue}然后做: json.NewEncoder(w).Encode(ResolutionValue{"foo"})有點蹩腳,有沒有辦法以某種方式確保完整性?
1 回答

ABOUTYOU
TA貢獻1812條經驗 獲得超5個贊
從 Go 1.11 開始,不支持嵌套類型。
在我看來,您的修訂版看起來好多了。
編輯:可能與問題無關,但您可以使用類型嵌入來簡化您的類型。但是,請注意表示形式不同:
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("%s\n%s", a, b)
}
哪個打?。?/p>
{"Val":"","Whatever":0}
{"Val":"","Inner":{"Whatever":0}}
- 1 回答
- 0 關注
- 147 瀏覽
添加回答
舉報
0/150
提交
取消