Go to Go.遇到这个错误,没有找到原因或理由:
如果我创建一个结构,我显然可以分配和重新分配值没有问题:
type Person struct {
name string
age int
}
func main() {
x := Person{"Andy Capp", 98}
x.age = 99
fmt.Printf("age: %d\n", x.age)
}
Run Code Online (Sandbox Code Playgroud)
但如果结构是地图中的一个值:
type Person struct {
name string
age int
}
type People map[string]Person
func main() {
p := make(People)
p["HM"] = Person{"Hank McNamara", 39}
p["HM"].age = p["HM"].age + 1
fmt.Printf("age: %d\n", p["HM"].age)
}
Run Code Online (Sandbox Code Playgroud)
我得到cannot assign to p["HM"].age.就是这样,没有其他信息.http://play.golang.org/p/VRlSItd4eP
我找到了解决这个问题的方法 - incrementAge在Person上创建一个func,可以调用它,并将结果分配给map键,例如p["HM"] = p["HM"].incrementAge().
但是,我的问题是,这个"无法分配"错误的原因是什么,为什么不允许我直接分配结构值?
我正在这里阅读教程: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在那里?
有人可以帮助新手吗?
非常感谢。