I am trying to create some API docs programmatically, I have this:
type APIDoc struct {
Route string
ResolutionValue struct {
v string
}
}
and then I tried doing this:
json.NewEncoder(w).Encode(APIDoc.ResolutionValue{"foo"})
but it says that
APIDoc.ResolutionValue undefined (type APIDoc has no method ResolutionValue)
so I resorted to doing this:
type ResolutionValue struct {
v string
}
type APIDoc struct {
Route string
ResolutionValue ResolutionValue
}
and then doing:
json.NewEncoder(w).Encode(ResolutionValue{"foo"})
kinda lame tho, is there a way to ensure integrity somehow?
As of Go 1.11, nested types are not supported.
Your revision looks a lot nicer IMO.
Edit: Maybe unrelated to the question but you can use type embedding to simplify your types. However, note that the representation are different:
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
%s", a, b)
}
Which prints:
{"Val":"","Whatever":0}
{"Val":"","Inner":{"Whatever":0}}