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 [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/golang-nuts/4a705e62-68f0-4136-804b-826eea48bc9dn%40googlegroups.com.