Go to the template comparison operators with the missing card key

I can not find documentation about what type of return value is when trying a key on a map in which the key does not exist. From the Go goug tracker, it looks like “no value”

I am trying to compare two values ​​using the eq function, but it gives an error if the key does not 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 an empty "" string, as in Go itself.

Is there an easy way to compare a potentially nonexistent map value with another value?

+12
source share
2 answers

Use the index function:

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

playground example

The index function returns a null value for the map value type when the key is not on the map. The zero value for the card in the question is an empty string.

+19
source

You can first check if the key is on the map, and only perform a comparison, if any. You can check with another action {{if}} or with the action {{with}} , which also sets up the pipeline.

Using {{with}} :

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

Using another {{if}} :

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

Note that you can add {{else}} branches to cover other cases. Full coverage {{with}} :

 {{with .MyMap.KeyThatDoesntExist}} {{if eq . "mystring"}} Match {{else}} No match {{end}} {{else}} Key not found {{end}} 

Full coverage {{if}} :

 {{if .MyMap.KeyThatDoesntExist}} {{if eq .MyMap.KeyThatDoesntExist "mystring"}} Match {{else}} No match {{end}} {{else}} Key not found {{end}} 

Note that in all full coverage options, if the key exists, but the associated value is "" , this will also lead to "Key not found" .

Try them on the go playground .

+2
source

All Articles