无法对结构变量进行赋值。

huangapple go评论68阅读模式
英文:

Can't assign to struct variable

问题

我有一个地图

var users = make(map[int]User)

我正在填充地图,一切都很好。稍后,我想给User的一个值赋值,但是我得到了一个错误。

type User struct {
  Id int
  Connected bool
}

users[id].Connected = true   // 错误

我还尝试编写一个函数来赋值,但也不起作用。

英文:

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.

答案1

得分: 8

例如,

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

输出:

map[42:{42 false}]
map[42:{42 true}]
英文:

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

答案2

得分: 2

在这种情况下,将指针存储在映射中而不是结构体是有帮助的:

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


输出:

&main.User{Id:314, Connected:false}
&main.User{Id:314, Connected: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}

huangapple
  • 本文由 发表于 2013年4月13日 13:00:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/15984423.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定