0

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?

  • 1
    Are you trying to implement an inner type? If so, that is really hard to do without making it messy. I'd suggest going with your second option. https://stackoverflow.com/questions/24809235/initialize-a-nested-struct-in-golang – ssemilla Oct 29 '18 at 05:03

1 Answers1

0

As of Go 1.11, nested types are not supported.

Proposal discussion

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\n%s", a, b)

}

Which prints:

{"Val":"","Whatever":0}
{"Val":"","Inner":{"Whatever":0}}
ssemilla
  • 3,900
  • 12
  • 28
  • yeah you may want to mention that I can just do `ResolutionValue` instead of `ResolutionValue ResolutionValue`, I just learned that a few minutes ago –  Oct 29 '18 at 05:23
  • For example, `Inner` here: https://stackoverflow.com/questions/53039039/creating-json-from-struct-not-struct-value –  Oct 29 '18 at 05:24
  • I'd edit the answer, but based from what you were trying to accomplish, it was more of an inner struct/type. – ssemilla Oct 29 '18 at 05:28