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

use*_*176 4 syntax dictionary if-statement go

我正在这里阅读教程: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"])
    }

}
Run Code Online (Sandbox Code Playgroud)

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

if temp, hero := superhero["Superman"]; hero {
Run Code Online (Sandbox Code Playgroud)

if temp对于局外人来说,这似乎是荒谬的,因为 temp 甚至没有在任何地方定义。那会实现什么?然后hero := superhero["Superman"]看起来像是一个任务。但是分号是做什么的呢?为什么决赛hero在那里?

有人可以帮助新手吗?

非常感谢。

Him*_*shu 5

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

i, ok := m["route"]
Run Code Online (Sandbox Code Playgroud)

在此语句中,第一个值 (i) 被分配给存储在键“route”下的值。如果该键不存在,则 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")
    }

}
Run Code Online (Sandbox Code Playgroud)

游乐场示例