7
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ぶぅちゃんズAdvent Calendar 2019

Day 15

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

Last updated at Posted at 2019-12-14

エラー

こういう構造体があって

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

コメント

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

参考

7
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?