#Check for existence of key in map of maps

10 messages · Page 1 of 1 (latest)

hallow canyon
#

I am familiar with the way to check if a key already exists in a map, such as:

  m := make(map[int]int)
  m[1] = 2
  val, ok := m[1] // gives 2, true
  val, ok := m[2] // gives 0, false

I can use a similar expression for a map of maps and it seems to compile and give the correct result:

m := make(map[int]map[int]string)
if val, ok := m[0][0]; ok {
  fmt.Println("key exists, corresponding value: ", val) // does not print
}

Is this the proper way to implement 2d maps if what I mainly want is to quickly check for the existence of a given 2d key (basically, an xy grid point as a key). Or would it be better to use a 1d map with a hash function, or even struct and iterate through the map checking for equality of keys?

lavish frost
#

Nope!

You need to do two step check, because if the outter key does not exist, it would panic. It means your are trying to access inner map on nil.


if outerMap, ok := nestedMap[1]; ok {
    if value, innerKeyExists := outerMap[10]; innerKeyExists {
        fmt.Println("Value:", value)
    } else {
        fmt.Println("Inner key doesn't exist")
    }
}

rapid charm
#

you do not need 2 explicit steps, reads from a nil map do not panic

proven knoll
hallow canyon
proven knoll
hallow canyon
#

Right, a bijection like the spiral map would work well as long as i dont overflow, which is until i reach sqrt(maxint)

hallow canyon
# rapid charm you do not need 2 explicit steps, reads from a nil map do not panic

okay, follow up question - would this also work for even higher dimensional maps? Also, what would the value it gets from reading a nil map be? just nil again? Are there "different" kinds of nils for different types? Like the compiler knows the value of the outer map is map[int]string, so it knows to throw a nil value of that type, and if it tries reading from a nil map[int]string, it knows to throw a nil string (which is just the empty string afaik). Sorry if what im saying doesn't make any sense.

rapid charm
#

reading from a map always returns the value stored for that key or the zero value for the element type, if there is no such key, regardless of the map value