我正在这里阅读教程:http://www.newthinktank.com/2015/02/go-programming-tutorial/ 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 temp, hero := superhero["Superman"]; hero {
Like if temp
对于局外人来说似乎很荒谬,因为 temp 甚至没有在任何地方定义。那会实现什么?然后hero := superhero["Superman"]
看起来像是一个任务。但是分号是做什么的呢?为什么是决赛hero
there?
有人可以帮助新手吗?
非常感谢。
二值赋值测试键是否存在:
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")
}
}
游乐场示例 https://play.golang.org/p/F_Ow0PoKXEP
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)