【问题标题】:Go template comparison operators on missing map key缺少映射键上的模板比较运算符
【发布时间】:2016-04-27 07:20:13
【问题描述】:

在尝试将键插入不存在该键的映射时,我找不到任何有关返回值类型的文档。从 Go 错误跟踪器来看,它似乎是一个特殊的“无价值”

我正在尝试使用 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 本身中。

有没有一种简单的方法来比较一个可能不存在的地图值和另一个值?

【问题讨论】:

    标签: dictionary go go-templates


    【解决方案1】:

    使用索引功能:

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

    playground example

    当键不在映射中时,index 函数返回映射值类型的零值。问题中地图的零值是空字符串。

    【讨论】:

    • 也适用于旧版本的 Go,与使用 {{if}}/{{with}} 的解决方案不同
    • @MuffinTop 我可以理解 Qs & As 的适度,但是 cmets 可以更广泛一些,不是吗?
    • KeyThatDoesntExist 可能以布尔值(可能是false)的形式存在时,是否能成功?当booleanValue 为假时,似乎if index .MyMap "booleanValue" 将失败。你知道检查布尔值是否存在的方法吗?
    【解决方案2】:

    您可以先检查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 上试试这些。

    【讨论】:

    • 很好的答案,只是想指出我发现的一个警告。如果键的值为空字符串,则此方法不起作用。 GoPlay
    • @LiamKelly 是的,你是对的,因为值类型的零值被视为false 条件。另一个(接受的)答案也是如此。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-28
    • 1970-01-01
    • 1970-01-01
    • 2020-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多