gpt4 book ai didi

dictionary - 缺少映射键上的模板比较运算符

转载 作者:IT老高 更新时间:2023-10-28 13:06:59 25 4
gpt4 key购买 nike

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

我正在尝试使用 eq 函数比较两个值,但如果 key 不存在,则会出错

例子:

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

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

导致错误调用 eq: invalid type for comparison

据此,我假设 nil 值不是空字符串 "" ,因为它在 Go 本身中。

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

最佳答案

使用索引功能:

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

playground example

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

关于dictionary - 缺少映射键上的模板比较运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34917099/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com