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.
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}]
                        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])
}
Playground
Output:
&main.User{Id:314, Connected:false}
&main.User{Id:314, Connected:true}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With