Map to struct and vice versa

167 views
Skip to first unread message

Nick Keets

unread,
May 17, 2021, 5:26:14 AM5/17/21
to golang-nuts
Is there an easy way to go from a map to a struct and vice versa? e.g. going from:
    m := map[string]interface{}{"a": "x", "b": 5}

to an instance of:
  type T struct {
    A string
    B int
  }

I can do this going through JSON (marshal the map, unmarshal into struct),
but is there a more direct way?

Amnon

unread,
May 17, 2021, 5:28:54 AM5/17/21
to golang-nuts

Mock ***

unread,
May 17, 2021, 7:53:10 AM5/17/21
to golang-nuts

Hi Nick,

I understand , please check if this pkg may help you https://github.com/fatih/structs,

Thanks

Howard C. Shaw III

unread,
May 17, 2021, 11:22:25 AM5/17/21
to golang-nuts
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


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.

Nick Keets

unread,
May 18, 2021, 2:59:07 AM5/18/21
to golang-nuts
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.


--
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...@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.
Reply all
Reply to author
Forward
0 new messages