[go-nuts] Initialize map for struct

8,787 views
Skip to first unread message

Archos

unread,
May 20, 2010, 5:49:32 PM5/20/10
to golang-nuts
Having a map into a struct, I was expecting that using `new(struct)` I
would get a full struct initialized (to zero) included the map but it
has to be manually initialized.

===
package main

import (
"fmt"
)

type version struct {
A int
B int
}

type T struct {
Name string
Versions map[byte]version
}


func main() {
v := version{12, 33}

// map manually initialized
var t T
t.Name = "welcome to Miami"
t.Versions = make(map[byte]version)
t.Versions[1] = v

// faills because the map is uninitialized
t2 := new(T)
t2.Versions[2] = v

fmt.Printf("%T : %v\n", t2,t2)
}
===

Kevin Ballard

unread,
May 20, 2010, 5:59:10 PM5/20/10
to Archos, golang-nuts
The zero value for a map is nil.

-Kevin Ballard
--
Kevin Ballard
http://kevin.sb.org
kbal...@gmail.com

jimmy frasche

unread,
May 20, 2010, 6:01:27 PM5/20/10
to Archos, golang-nuts
This is the specified behavior. Please attempt to consult the
documentation before posting.

Ian Lewis

unread,
May 21, 2014, 7:17:21 AM5/21/14
to golan...@googlegroups.com, Archos
That's not a very helpful response at all. You should at least give the guy a pointer to the correct doco and help the rest of us golang n00bs.

@Archos 
Here are a couple of links I found useful:


So in essence you will need a constructor func(tion) for your struct to return a pointer to the newly created object. You can't use the struct directly without instantiating it first. This is my understanding so far.

Jan Mercl

unread,
May 21, 2014, 7:25:39 AM5/21/14
to Ian Lewis, golang-nuts, Archos
On Wed, May 21, 2014 at 1:17 PM, Ian Lewis <ian....@crowdsurge.com> wrote:
> So in essence you will need a constructor func(tion) for your struct to
> return a pointer to the newly created object. You can't use the struct
> directly without instantiating it first. This is my understanding so far.

In the OP case, given

type T struct {
Name string
Versions map[byte]version
}

one can initilaize like

instance := &T{Name: "foo", Versions: map[byte]version{}}

ie. a constructor function is not always needed.

-j

Ian Lewis

unread,
May 21, 2014, 7:27:48 AM5/21/14
to golan...@googlegroups.com, Ian Lewis, Archos
Thank you! That's very helpful to know.

Cheers
Reply all
Reply to author
Forward
0 new messages