缺少映射键的模板比较运算符
Go template comparison operators on missing map key
在尝试键入不存在键的映射时,我无法找到任何关于 return 值类型的文档。从 Go 错误跟踪器来看,它似乎是一个特殊的 'no value'
我正在尝试使用 eq
函数比较两个值,但如果密钥不存在,它会给出错误
示例:
var themap := map[string]string{}
var MyStruct := struct{MyMap map[string]string}{themap}
{{if eq .MyMap.KeyThatDoesntExist "mystring"}}
{{.}}
{{end}
结果 error calling eq: invalid type for comparison
由此我假设 nil 值不是 Go 本身的空字符串 ""
。
是否有一种简单的方法来比较可能不存在的地图值和另一个值?
你可以先检查key是否在map中,存在才比较。您可以检查另一个 {{if}}
操作或使用同样设置管道的 {{with}}
操作。
使用{{with}}
:
{{with .MyMap.KeyThatDoesntExist}}{{if eq . "mystring"}}Match{{end}}{{end}}
使用另一个 {{if}}
:
{{if .MyMap.KeyThatDoesntExist}}
{{if eq .MyMap.KeyThatDoesntExist "mystring"}}Match{{end}}{{end}}
请注意,您可以添加 {{else}}
个分支来涵盖其他情况。完全覆盖 {{with}}
:
{{with .MyMap.KeyThatDoesntExist}}
{{if eq . "mystring"}}
Match
{{else}}
No match
{{end}}
{{else}}
Key not found
{{end}}
完全覆盖{{if}}
:
{{if .MyMap.KeyThatDoesntExist}}
{{if eq .MyMap.KeyThatDoesntExist "mystring"}}
Match
{{else}}
No match
{{end}}
{{else}}
Key not found
{{end}}
请注意,在所有的全覆盖变体中,如果键存在但关联值为 ""
,这也将导致 "Key not found"
.
在 Go Playground 上试试这些。
使用索引函数:
{{if eq (index .MyMap "KeyThatDoesntExist") "mystring"}}
{{.}}
{{end}}
index
函数 returns 当键不在映射中时映射值类型的零值。问题中地图的零值是空字符串。
在尝试键入不存在键的映射时,我无法找到任何关于 return 值类型的文档。从 Go 错误跟踪器来看,它似乎是一个特殊的 'no value'
我正在尝试使用 eq
函数比较两个值,但如果密钥不存在,它会给出错误
示例:
var themap := map[string]string{}
var MyStruct := struct{MyMap map[string]string}{themap}
{{if eq .MyMap.KeyThatDoesntExist "mystring"}}
{{.}}
{{end}
结果 error calling eq: invalid type for comparison
由此我假设 nil 值不是 Go 本身的空字符串 ""
。
是否有一种简单的方法来比较可能不存在的地图值和另一个值?
你可以先检查key是否在map中,存在才比较。您可以检查另一个 {{if}}
操作或使用同样设置管道的 {{with}}
操作。
使用{{with}}
:
{{with .MyMap.KeyThatDoesntExist}}{{if eq . "mystring"}}Match{{end}}{{end}}
使用另一个 {{if}}
:
{{if .MyMap.KeyThatDoesntExist}}
{{if eq .MyMap.KeyThatDoesntExist "mystring"}}Match{{end}}{{end}}
请注意,您可以添加 {{else}}
个分支来涵盖其他情况。完全覆盖 {{with}}
:
{{with .MyMap.KeyThatDoesntExist}}
{{if eq . "mystring"}}
Match
{{else}}
No match
{{end}}
{{else}}
Key not found
{{end}}
完全覆盖{{if}}
:
{{if .MyMap.KeyThatDoesntExist}}
{{if eq .MyMap.KeyThatDoesntExist "mystring"}}
Match
{{else}}
No match
{{end}}
{{else}}
Key not found
{{end}}
请注意,在所有的全覆盖变体中,如果键存在但关联值为 ""
,这也将导致 "Key not found"
.
在 Go Playground 上试试这些。
使用索引函数:
{{if eq (index .MyMap "KeyThatDoesntExist") "mystring"}}
{{.}}
{{end}}
index
函数 returns 当键不在映射中时映射值类型的零值。问题中地图的零值是空字符串。