nil maps

322 views
Skip to first unread message

Alex Dvoretskiy

unread,
Oct 17, 2017, 12:52:45 AM10/17/17
to golang-nuts
Hello, Golang Nuts!

I have an interesting question about maps. What is the possible usage of nil maps, which can be declared like "var m map[string]int"? You can't write to nil map but have an option to create it.

Perhaps there is no use at all and this is just language specific feature?

Thank you.

Dan Kortschak

unread,
Oct 17, 2017, 1:03:13 AM10/17/17
to Alex Dvoretskiy, golang-nuts
If you only need the map conditionally, you need to declare it and then
conditionally make it.

```
var m map[string]int
if needMap {
    m = make(map[string]int)
}
```

Christian Himpel

unread,
Oct 17, 2017, 2:32:38 AM10/17/17
to Dan Kortschak, Alex Dvoretskiy, golang-nuts
The spec defines: "A nil map is equivalent to an empty map except that no elements may be added." https://golang.org/ref/spec#Map_types

You could return a nil map, if you have no elements to add, and a caller would just need to read.

--
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/d/optout.

Rob Pike

unread,
Oct 17, 2017, 2:47:09 AM10/17/17
to Christian Himpel, Dan Kortschak, Alex Dvoretskiy, golang-nuts
A nil map is like a regular map but it has nothing in it, cannot grow, and takes zero space.

-rob


To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe@googlegroups.com.

For more options, visit https://groups.google.com/d/optout.

--
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+unsubscribe@googlegroups.com.

Thomas Bushnell, BSG

unread,
Oct 17, 2017, 1:39:46 PM10/17/17
to Alex Dvoretskiy, golang-nuts
Here's a case that comes up for me:

type table map[string]map[string]string

func (t table) add(x, y, z string) {
  if t[x] == nil {
    t[x] = make(map[string]string)
  }
  t[x][y] = z
}

func (t table) get(x, y string) string {
  return t[x][y]
}

The fact that t[x] can be indexed even if it hasn't been created makes this much simpler.

--
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.

Alex Dvoretskiy

unread,
Oct 18, 2017, 6:38:43 PM10/18/17
to golang-nuts

roger peppe

unread,
Oct 19, 2017, 1:22:26 PM10/19/17
to Alex Dvoretskiy, golang-nuts
Or taking it a bit further: https://play.golang.org/p/g4uF2QjiJQ

Alex Dvoretskiy

unread,
Oct 27, 2017, 7:44:23 PM10/27/17
to golang-nuts
wow, super impressed!
Reply all
Reply to author
Forward
0 new messages