Jayson Bailey
Jayson Bailey

Reputation: 1004

Can't assign to struct variable

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.

Upvotes: 5

Views: 3848

Answers (3)

Saeed Firouzi
Saeed Firouzi

Reputation: 61

To assign a value to an item on a struct on a map in go you must make the object first. I'll continue on your own example:

type User struct {
  Id int
  Connected bool
}

users[id] = User{
    Id:        id,
    Connected: true,
}

and if you want to assign to an existing key you should find it on your map first, like:

if u,ok := users[id]; ok {
    u.Connected = false
    users[id] = u
}

Upvotes: 1

zzzz
zzzz

Reputation: 91419

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}

Upvotes: 2

peterSO
peterSO

Reputation: 166885

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

Upvotes: 8

Related Questions