What is the different between make() and {} to initialize a map

7,314 views
Skip to first unread message

Isaac Mosquera

unread,
Sep 5, 2013, 4:13:41 PM9/5/13
to golan...@googlegroups.com
Is there a difference between the following 2 lines of code:

m := make(map[string]int)

and the following: 

m := map[string]int{}


are they initialized the same? is one preferred over another?

Brad Fitzpatrick

unread,
Sep 5, 2013, 4:15:46 PM9/5/13
to Isaac Mosquera, golang-nuts
They're the same.

The make form lets you say:

 m := make(map[string]int, 100)

Where 100 is the expected capacity.




--
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 golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

andrey mirtchovski

unread,
Sep 5, 2013, 4:18:56 PM9/5/13
to Brad Fitzpatrick, Isaac Mosquera, golang-nuts
> They're the same.
>
> The make form lets you say:
>
> m := make(map[string]int, 100)
>
> Where 100 is the expected capacity.

and the other form allows you to set some of the elements in the map
"using the usual composite literal syntax with colon-separated
key-value pairs": http://golang.org/doc/effective_go.html#maps

Kyle Lemons

unread,
Sep 6, 2013, 2:12:54 PM9/6/13
to Isaac Mosquera, golang-nuts
On Thu, Sep 5, 2013 at 1:13 PM, Isaac Mosquera <is...@sharethis.com> wrote:
Similar to new(Struct) vs Struct{}, I use them in slightly different ways:

1) If the value is done and I don't need to add anything to it before releasing it off into the world, I use the {} version
2) If I'm planning on adding things to it (usually programmatically) I use the make() (or new()) version.

The idea is that this hints to me in the future where to add new starter values to it.  In (1), I insert them between the braces, in (2) I add them in code somewhere.

YMMV

Kyle Lemons

unread,
Sep 6, 2013, 2:13:22 PM9/6/13
to Isaac Mosquera, golang-nuts
On Fri, Sep 6, 2013 at 11:12 AM, Kyle Lemons <kev...@google.com> wrote:
On Thu, Sep 5, 2013 at 1:13 PM, Isaac Mosquera <is...@sharethis.com> wrote:
Is there a difference between the following 2 lines of code:

m := make(map[string]int)

and the following: 

m := map[string]int{}


are they initialized the same? is one preferred over another?

Similar to new(Struct) vs Struct{}, I use them in slightly different ways:

vs &Struct{}, sorry
Reply all
Reply to author
Forward
0 new messages