Using reflect, is there a way to discover the type of a map key and value?

1,477 views
Skip to first unread message

dco...@google.com

unread,
May 1, 2012, 1:39:39 PM5/1/12
to golan...@googlegroups.com
I am trying to write a bit of code that will take serialized data, and stuff it into an (arbitrary-ish) struct. Think taking the text output of a database query.
I know what struct the data is supposed to fit into, and I assume for this exercise that all of the data is parseable.

For Example, given:

type FRQ struct {
                Row   int
                GroupBy map[string]string
                Points []struct {
                        Timedate time.Time
                        Count    float64
                }
        }

        Rows := make([]FRQ, result.Len)

        for i := range Rows {
                Rows[i].GroupBy = make(map[string]string)
                err := result.Decode(i, &Rows[i])
                fmt.Printf("Got %v\n", Rows[i])
                if err != nil {
                        log.Fatal(err)
                }
        }

and func Decode(val interface{}, data []string) error I want to fill in Rows[i]

with a little help from an auxiliary routine to handle the time.Time conversion, I can do most of this
by walking through the struct and using reflect to figure what conversion I need from the text input.
If I cheat by knowing that GroupBy is a map[string][string] I can perform this perfectly.

But I can't see how to discover the types of the key and value of the map based the incoming interface.
I assume I'm missing something, but what?

I attach the decoder. 

Thanks,
David.
decoder.go

Jesse McNelis

unread,
May 1, 2012, 2:34:32 PM5/1/12
to dco...@google.com, golan...@googlegroups.com
On Wed, May 2, 2012 at 3:39 AM, <dco...@google.com> wrote:
> But I can't see how to discover the types of the key and value of the map
> based the incoming interface.

reflect.Type.Key() and reflect.Type.Elem() is probably what you want.

"Key() returns a map type's key type."
"Elem() returns a type's element type."
http://golang.org/pkg/reflect/#Type

--
=====================
http://jessta.id.au
Reply all
Reply to author
Forward
0 new messages