1

Code:

type t_struct struct {
    player string
    id     int
}

func main() {
    dataA := make(map[string]t_struct)
    dataB := make(map[string]*t_struct)

    var playerA t_struct
    playerA.player = "tom"
    playerA.id = 1
    dataA["classA"] = playerA
    dataA["classA"].id = 2 // ERROR, why?

    playerB := new(t_struct)
    dataB["classB"] = playerB
    dataB["classB"].player = "rick"
    dataB["classB"].id = 3
}

And got error:

cannot assign to dataA["classA"].id

I wonder why dataA["classA"].id = 2 not worked but dataB["classB"].id = 3 did? Is it the only way to save struct pointer into map if you want to modify member value of it?

4

1 回答 1

7

The expression dataA["classA"] if of type t_struct. That means that

dataA["classA"].id = 2

is equvalent to e.g.

t_struct{"some player", 42}.id = 2

Playground

IOW, the struct value has no "home" and changing its field cannot be persisted. As the only possibility is a programmer's mistake, the compiler flags an error.

OTOH:

dataB["classB"]

has type *t_struct. Then

dataB["classB"].id = 3

is equivalent to

(*t_struct)(somePointer).id = 3

I.e., this lvalue has a "home". It's where the pointer points to. The change to the field will be "recorded" there and it is thus a valid Go operation (simple assignment to a struct field where the struct is referenced by a pointer).

于 2013-04-17T11:50:57.883 回答