英文:
Can't assign to struct variable
问题
我有一个地图
var users = make(map[int]User)
我正在填充地图,一切都很好。稍后,我想给User的一个值赋值,但是我得到了一个错误。
type User struct {
Id int
Connected bool
}
users[id].Connected = true // 错误
我还尝试编写一个函数来赋值,但也不起作用。
英文:
I've got a map
var users = make(map[int]User)
I'm filling the map and all is fine. Later, I want to assign to one of the values of User, but I get an error.
type User struct {
Id int
Connected bool
}
users[id].Connected = true // Error
I've also tried to write a function that assigns to it, but that doesn't work either.
答案1
得分: 8
例如,
package main
import "fmt"
type User struct {
Id int
Connected bool
}
func main() {
users := make(map[int]User)
id := 42
user := User{id, false}
users[id] = user
fmt.Println(users)
user = users[id]
user.Connected = true
users[id] = user
fmt.Println(users)
}
输出:
map[42:{42 false}]
map[42:{42 true}]
英文:
For example,
package main
import "fmt"
type User struct {
Id int
Connected bool
}
func main() {
users := make(map[int]User)
id := 42
user := User{id, false}
users[id] = user
fmt.Println(users)
user = users[id]
user.Connected = true
users[id] = user
fmt.Println(users)
}
Output:
map[42:{42 false}]
map[42:{42 true}]
答案2
得分: 2
在这种情况下,将指针存储在映射中而不是结构体是有帮助的:
package main
import "fmt"
type User struct {
Id int
Connected bool
}
func main() {
key := 100
users := map[int]*User{key: &User{Id: 314}}
fmt.Printf("%#v\n", users[key])
users[key].Connected = true
fmt.Printf("%#v\n", users[key])
}
输出:
&main.User{Id:314, Connected:false}
&main.User{Id:314, Connected:true}
英文:
In this case it is helpful to store pointers in the map instead of a structure:
package main
import "fmt"
type User struct {
Id int
Connected bool
}
func main() {
key := 100
users := map[int]*User{key: &User{Id: 314}}
fmt.Printf("%#v\n", users[key])
users[key].Connected = true
fmt.Printf("%#v\n", users[key])
}
Output:
&main.User{Id:314, Connected:false}
&main.User{Id:314, Connected:true}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论