2 回答
TA贡献1829条经验 获得超9个赞
例如,
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}]
TA贡献1856条经验 获得超5个赞
在这种情况下,将指针存储在映射中而不是结构中是有帮助的:
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}
- 2 回答
- 0 关注
- 152 浏览
添加回答
举报