Sam*_*Sam 12 dictionary go go-templates
在尝试键入不存在键的映射时,我无法找到有关返回值类型的任何文档.从Go bug跟踪器看来它似乎是一种特殊的"无价值"
我正在尝试使用该eq函数比较两个值,但如果该键不存在则会出错
例:
var themap := map[string]string{}
var MyStruct := struct{MyMap map[string]string}{themap}
{{if eq .MyMap.KeyThatDoesntExist "mystring"}}
{{.}}
{{end}
Run Code Online (Sandbox Code Playgroud)
结果是 error calling eq: invalid type for comparison
从这里我假设nil值不是""Go 字符串中的空字符串.
有没有一种简单的方法来比较可能不存在的地图值和另一个值?
Cer*_*món 19
使用索引功能:
{{if eq (index .MyMap "KeyThatDoesntExist") "mystring"}}
{{.}}
{{end}}
Run Code Online (Sandbox Code Playgroud)
当键不在映射中时,index函数返回映射值类型的零值.问题中地图的零值是空字符串.
| 归档时间: |
|
| 查看次数: |
4093 次 |
| 最近记录: |