0
Help us understand the problem. What are the problem?

More than 1 year has passed since last update.

posted at

updated at

golangでmapの中の構造体を書き換えようとしたらcannot assign to struct field in mapになる

エラー

こういう構造体があって

type User struct {
  Id int
  Connected bool
}

User{0, true}という構造体をmapに追加してその要素を書き換えようとすると

users := map[int]User{0: User{0, true}}
users[0].Connected = false

cannot assign to struct field users[0].Connected in mapとエラーが出る。

解決策

構造体ごと書き換える

users := map[int]User{0: User{0, true}}
u, ok := users[0]
if ok {
  u.Connected = false
}
users[0] = u

値をポインタにする

users := map[int]*User{0: &User{0, true}}
users[0].Connected = false

コメント

他にいいやり方ないですかね。

参考

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Sign upLogin
0
Help us understand the problem. What are the problem?