Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't assign to struct variable

Tags:

go

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.

like image 219
Jayson Bailey Avatar asked Apr 13 '13 05:04

Jayson Bailey


2 Answers

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}]
like image 152
peterSO Avatar answered Oct 01 '22 12:10

peterSO


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}
like image 22
zzzz Avatar answered Oct 01 '22 11:10

zzzz