Unable to assign struct variable

I have a map

var users = make(map[int]User)

I fill out the card and everything is in order. Later I want to assign one of the User values, but I get an error.

type User struct {
  Id int
  Connected bool
}

users[id].Connected = true   // Error

I also tried to write a function that is assigned to it, but that doesn't work either.

+5
source share
2 answers

For instance,

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)
}

Conclusion:

map[42:{42 false}]
map[42:{42 true}]
+7
source

In this case, it is useful to store pointers on a 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])
}

Playground


Conclusion:

&main.User{Id:314, Connected:false}
&main.User{Id:314, Connected:true}
+2
source

All Articles