reflect: how to initialize a struct field that is a map?

1,027 views
Skip to first unread message

Hai Thanh Nguyen

unread,
Jun 15, 2014, 7:43:40 AM6/15/14
to golan...@googlegroups.com
For example we have a struct:
type Test struct {
   f map[string]string
}

if we initialize an instance of that struct with
o := reflect.New(reflect.TypeOf(Test{}))

now the field f is nil
I attempt to set the field f to a new map:
o.FieldByName("f").Set(reflect.MakeMap(...))
however this fails because the field is nil, it cannot be set

so how do I initialize the field?
basically it's something like `o.f = make(map[string]string)`

egon

unread,
Jun 15, 2014, 8:19:48 AM6/15/14
to golan...@googlegroups.com
You cannot set private fields with reflection.

Hai Thanh Nguyen

unread,
Jun 15, 2014, 2:07:30 PM6/15/14
to golan...@googlegroups.com
Oh sorry I was in a hurry and typed it wrong, it should have been F, this question is not about that (ofc. I know reflection doesn't work with unexported field).
It's about Initializing a field which is a map that is nil when the struct get created.

Question rewritten:
For example we have a struct:
type Test struct {
   F map[string]string
}

if we initialize an instance of that struct with
o := reflect.New(reflect.TypeOf(Test{}))

now the field F is nil
I attempt to set the field F to a new map:
o.FieldByName("F").Set(reflect.MakeMap(...))
however this fails with something like "cannot set to zero value" because the field is nil, it cannot be set

so how do I initialize the field?
basically it's something like `o.F = make(map[string]string)`

Carlos Castillo

unread,
Jun 15, 2014, 2:21:32 PM6/15/14
to golan...@googlegroups.com
You cant set the field of a pointer (it doesn't have fields), you must use Elem, to get the actual struct.

Also, you should use the playground: http://play.golang.org/p/ovPA6i7g_r

egon

unread,
Jun 16, 2014, 3:44:18 AM6/16/14
to golan...@googlegroups.com
On Sunday, 15 June 2014 21:07:30 UTC+3, Hai Thanh Nguyen wrote:
Oh sorry I was in a hurry and typed it wrong, it should have been F, this question is not about that (ofc. I know reflection doesn't work with unexported field).
It's about Initializing a field which is a map that is nil when the struct get created.


Also, quite often reflection can be replaced with something better.

+ egon
Reply all
Reply to author
Forward
0 new messages