dictionary - 带有映射的 "if"语句中的 Golang 语法

标签 dictionary if-statement go syntax

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

在“ map 中的 map ”部分,它具有:

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"] 看起来像一个作业。但是分号在做什么呢?为什么最后的英雄在那里?

有人可以帮助新手吗?

非常感谢。

最佳答案

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

在 go 中类似于写作:

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

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

否则 false

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

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

关于dictionary - 带有映射的 "if"语句中的 Golang 语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52705926/

相关文章:

java - 如何在java中运行时比较两个长值

python - 迭代数据框并根据条件替换值

mongodb - 根据 Go 子文档中的字段对 mongodb 查询进行排序

python - json.dump 无法序列化包含 python 列表的字典

以列为字典的 Pandas 数据透视表

c - 在 if 指令中读取 c 中的字符串

performance - 如何有效地在文件中插入 byte slice ?

json - 如何在golang中使用变量设置json标签?

ios - UIWebView href 打开 map 应用程序失败

python - 如何处理json空值