我正在阅读这里的教程: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 的每个查询都将返回一个可选的第二个参数,该参数将告知某个键是否存在
关于dictionary - 带有映射的 "if"语句中的 Golang 语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52705926/