Go template comparison operators on missing map key

Sam picture Sam · Jan 21, 2016 · Viewed 7.8k times · Source

I am unable to find any documentation regarding what the type of the return value is when attempting key into a map in which the key doesn't exist. From the Go bug tracker it appears to be a special 'no value'

I'm trying to compare two values using the eq function but it gives an error if the key doesn't exist

Example:

var themap := map[string]string{}  
var MyStruct := struct{MyMap map[string]string}{themap}

{{if eq .MyMap.KeyThatDoesntExist "mystring"}}
  {{.}}
{{end}

Results in error calling eq: invalid type for comparison

From this I assume that the nil value is not the empty string "" as it is in Go itself.

Is there a simple way to compare a potentially non-existent map value and another value?

Answer

Cerise Limón picture Cerise Limón · Jan 21, 2016

Use the index function:

{{if eq (index .MyMap "KeyThatDoesntExist") "mystring"}}
  {{.}}
{{end}}

playground example

The index function returns the zero value for the map value type when the key is not in the map. The zero value for the map in the question is the empty string.