2013-04-13 35 views
5

Ho una mappanon può assegnare a struct variabile

var users = make(map[int]User) 

sto riempiendo la mappa e tutto va bene. Più tardi, voglio assegnare a uno dei valori di Utente, ma ottengo un errore.

type User struct { 
    Id int 
    Connected bool 
} 

users[id].Connected = true // Error 

Ho anche provato a scrivere una funzione che assegna ad esso, ma che non funziona neanche.

+0

Bah, è stato un errore di battitura. –

+0

che errore di battitura? Non riesco a vederlo :( – OscarRyz

risposta

7

Per esempio,

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

uscita:

map[42:{42 false}] 
map[42:{42 true}] 
2

In questo caso è utile per memorizzare i puntatori nella mappa invece di una struttura:

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


uscita:

&main.User{Id:314, Connected:false} 
&main.User{Id:314, Connected:true} 
Problemi correlati