On Monday, 18 July 2016 10:33:44 UTC+3, fazal wrote: > > Fellow gophers, > > I'm having this dilemma of whether to embed related struct, or to have an > ID field pointing to resource in the DB. >
Note ensure that your ID is not generated from the Name, team names change and if you rely on it being based on the Name you end up with problems when changing team names. > > Say I have something like these types defined. > > type Team struct{ > ID string > Name string > } > > type Organization struct { > ID string > Name string > } > > Now my question is which is better, more idiomatic > > > // 1 > type Team struct{ > ID string > Name string > OrgID string > } > > > // 2 > type Team struct { > ID string > Name string > Organization Organization > > } > > Web applications I see mostly use 1, which is sensible as most of the time > you only just need Organization ID with Team. > But sometimes you just need to include a little bit more information > (mostly for JSON output). For that with 1 you'd have to define another type > that include both Team and Organization. > > With 2 the problem is you need to embed Organization type even if you just > needed the ID. Also you'd have to have `json:"omitempty"` everywhere since > you don't want empty fields in your JSON. > And that alone is not enough, some types would need to be changed to > pointer types within the struct since `omitempty` does consider them as > empty. > > I know I could use a mix of this, but that makes it difficult to create a > consistent API with a consistent format. > > Assuming it's mostly for web applications with JSON API endpoints, how do > you tackle this problem? > Two additional possibilities: https://play.golang.org/p/aTvCPj2h1P https://play.golang.org/p/PI5fNg42U9 -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.