Thanks everyone for your responses. structs is interesting, but archived, pre modules even. Using reflect directly also doesn't seem that bad and I do want error handling, so it looks like nothing beats JSON in terms of UI.
On Mon, May 17, 2021 at 6:22 PM Howard C. Shaw III <howardcs...@gmail.com> wrote: > The examples given in other responses are great if you need to handle > arbitrary or unknown maps and very much fit the 'easy way' part of your > initial question. But you also asked at the end 'is there a more direct > way?'. > > If you actually know what you are getting, you can code it entirely > directly: > > t := T{ > A: m["a"].(string), > B: m["b"].(int), > } > > and back again > > m2 := map[string]interface{}{} > m2["a"] = t.A > m2["b"] = t.B > > https://play.golang.org/p/4OY3QoA5Mr3 > > Why would you not do this? Because your assignment will panic if you pass > an m that is missing "a" or "b". Not fun. (Something like "panic: interface > conversion: interface {} is nil, not int") Of course, you can always > collect the values from the map into temporaries before creating the type > and handle any nils in that process. Or pass your map through a validation > step that ensures it is safe to convert before passing it to the conversion. > > -- > 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. > To view this discussion on the web visit > https://groups.google.com/d/msgid/golang-nuts/4a705e62-68f0-4136-804b-826eea48bc9dn%40googlegroups.com > <https://groups.google.com/d/msgid/golang-nuts/4a705e62-68f0-4136-804b-826eea48bc9dn%40googlegroups.com?utm_medium=email&utm_source=footer> > . > -- 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. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/CAPKajN7-MFbqF_ojECYmnBjye7jNXxu181E5%3DM%3D9Eif%3DM92bhw%40mail.gmail.com.