【问题标题】:Avoiding need for redundant check to map given zero value of string?避免需要冗余检查来映射给定的零值字符串?
【发布时间】:2020-02-24 09:37:52
【问题描述】:

我们有一个map[string]string,我假设这意味着从映射中检索到的字符串的零值是""

那么这不就意味着:

var userId, ok = params["user_id"];

if !ok || userId == "" {
    return 422, "Missing user_id in request"
}

和这个逻辑是一样的:

var userId = params["user_id"];

if  userId == "" {
    return 422, "Missing user_id in request"
}

只是确保我的理解是正确的。

【问题讨论】:

  • “和这个逻辑一样”。不,如果params 包含一个空字符串“”,则这些不等价。否则是的。

标签: dictionary go


【解决方案1】:

如果你打算存储值类型的零值就不一样了。

看这个例子:

m := map[string]string{
    "empty": "",
}

if v, ok := m["empty"]; ok {
    fmt.Printf("'empty' is present: %q\n", v)
} else {
    fmt.Println("'empty' is not present")
}
if v, ok := m["missing"]; ok {
    fmt.Printf("'missing' is present: %q\n", v)
} else {
    fmt.Printf("'missing' is not present")
}

它输出(在Go Playground上试试):

'empty' is present: ""
'missing' is not present

确实,如果您从不在地图中存储零值,您可以简单地使用if m[value] == zeroValue {}。这里有详细说明:How to check if a map contains a key in Go?

可以利用地图的这种“属性”来优雅地创建集合。见How can I create an array that contains unique strings?

而且使用这种“技术”还有另一个优点:您可以以紧凑的方式检查多个键的存在(您不能使用特殊的“逗号 ok”形式来做到这一点)。更多信息:Check if key exists in multiple maps in one condition

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-16
    • 1970-01-01
    • 2017-08-10
    • 1970-01-01
    • 1970-01-01
    • 2019-12-07
    • 1970-01-01
    相关资源
    最近更新 更多