登录
首页 >  Golang >  Go问答

带地图的“if”语句中的 Golang 语法

来源:stackoverflow

时间:2024-03-17 10:21:31 225浏览 收藏

Go语言中,“if”语句中的赋值测试可用于检查地图中键是否存在。该语句使用二值赋值测试,将键的值分配给第一个变量(“temp”),并将布尔值(“hero”)分配给第二个变量。布尔值指示键是否存在于地图中。如果键存在,“hero”为 true;否则,为 false。该测试非常有用,因为它允许开发者在不确定地图中数据的情况下检查特定键,并根据键是否存在执行不同的操作。

问题内容

我正在这里阅读教程:http://www.newthinktank.com/2015/02/go-programming-tutorial/

在“地图中的地图”部分有:

package main

import "fmt"

func main() {

    // we can store multiple items in a map as well

    superhero := map[string]map[string]string{
        "superman": map[string]string{
            "realname":"clark kent",
            "city":"metropolis",
        },

        "batman": map[string]string{
            "realname":"bruce wayne",
            "city":"gotham city",
        },
    }

    // we can output data where the key matches superman

    if temp, hero := superhero["superman"]; hero {
        fmt.println(temp["realname"], temp["city"])
    }

}

我不明白“if”语句。有人可以引导我完成这一行的语法吗:

if temp, hero := superhero["Superman"]; hero {

就像 if temp 对于局外人来说似乎毫无意义,因为 temp 甚至没有在任何地方定义。那会实现什么?然后 hero := superhero["superman"] 看起来像是一个作业。但是分号是做什么的呢?为什么最后的 hero 在那里?

有人可以帮助新手吗?

非常感谢。


解决方案


二值赋值测试键是否存在:

i, ok := m["route"]

在此语句中,第一个值 (i) 被赋予存储的值 在关键“路线”下。如果该键不存在,则 i 是值 类型的零值 (0)。第二个值 (ok) 是一个布尔值,如果满足以下条件则为 true 该键存在于地图中,如果不存在则为 false。

这种检查基本上是在我们不确定地图内部数据的情况下使用的。因此,我们只需检查特定的键,如果存在,我们将值分配给变量。这是一个 o(1) 检查。

在您的示例中,尝试在地图中搜索不存在的键:

package main

import "fmt"

func main() {

    // we can store multiple items in a map as well

    superhero := map[string]map[string]string{
        "superman": map[string]string{
            "realname": "clark kent",
            "city":     "metropolis",
        },

        "batman": map[string]string{
            "realname": "bruce wayne",
            "city":     "gotham city",
        },
    }

    // we can output data where the key matches superman

    if temp, hero := superhero["superman"]; hero {
        fmt.println(temp["realname"], temp["city"])
    }

    // try to search for a key which doesnot exist

    if value, ok := superhero["hulk"]; ok {
        fmt.println(value)
    } else {
        fmt.println("key not found")
    }

}

Playground Example

if temp, hero := superhero["superman"]; hero

在 go 中类似于编写:

temp, hero := superhero["Superman"]
if hero {
    ....
}

这里将“superman”映射到一个值,英雄将是true

否则 false

在 go 中,对映射的每个查询都会返回一个可选的第二个参数,该参数将告诉某个键是否存在

https://play.golang.org/p/Hl7MajLJV3T

今天关于《带地图的“if”语句中的 Golang 语法》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>