determine passed key and value types

77 views
Skip to first unread message

Eric Brown

unread,
May 25, 2016, 3:09:40 PM5/25/16
to golang-nuts
Is there a way, possibly using reflection, to pass a generic map reference to a function... and for that function to determine the key and value types of that map (without it being specified in the parameters)?

Tim K

unread,
May 25, 2016, 3:33:53 PM5/25/16
to golang-nuts

Eric Brown

unread,
May 25, 2016, 3:43:13 PM5/25/16
to golang-nuts

Man, still learning goLang... and didn't realize this would be that simple.  I highly appreciate your help! 

Eric Brown

unread,
May 25, 2016, 3:48:58 PM5/25/16
to golang-nuts
One last question:  since maps can not be accessed concurrently without a panic, if I attempt to use reflect on it while it's in use somewhere else being written to... will this cause an issue?


On Wednesday, May 25, 2016 at 2:33:53 PM UTC-5, Tim K wrote:

Roberto Zanotto

unread,
May 25, 2016, 4:13:08 PM5/25/16
to golang-nuts
Depends what you are doing with reflection. If you are updating keyvals concurrently, it's a problem.
If you take the reflect.Type value (with reflect.TypeOf(m)), then you can inspect it however you want while the map is being modified.

Eric Brown

unread,
May 25, 2016, 4:21:18 PM5/25/16
to golang-nuts
I'm just inspecting it, so nothing is being modified.  Appreciate your response, Roberto.

keith....@gmail.com

unread,
May 25, 2016, 8:57:17 PM5/25/16
to golang-nuts
You can only access the type safely.  If another goroutine is writing to the map both map reads and writes (reflect or otherwise) are unsafe.
Comparison against nil would also be ok.

Roberto Zanotto

unread,
May 25, 2016, 10:40:05 PM5/25/16
to golang-nuts, keith....@gmail.com
Yeah, totally, I'm afraid I didn't make it clear enough.
When you call reflect.TypeOf(m) you get some read-only data structure (an interface, actually) that represents the map's type,
but is not tied to the map itself (it's allocated separately from the map value).
Reply all
Reply to author
Forward
0 new messages