Cannot take the address of map element

前端 未结 2 1151
旧巷少年郎
旧巷少年郎 2021-01-29 05:34

I want to find out why

x:= odsMap[segRef]
x.GetValue(\"@OriginDestinationKey\")

works, but this does not:

odsMap[segRef].GetVal         


        
2条回答
  •  闹比i
    闹比i (楼主)
    2021-01-29 06:03

    Map index expressions are not addressable, because the internals of a map may change when a new entry is added to it, so the spec intentionally does not allow taking its address (this gives greater freedom for map implementations).

    This means if you store non-pointers in the map, and you want to call a method of a stored value that has a pointer receiver, that would require to take the address of the non-pointer value (to be used as the receiver), but since map index expressions are not addressable, that results in a compile-time error.

    A workaround is to store pointer values in the map, so there is no need to take the address of an index expression, because it's already a pointer. An example of this can be seen in this answer: Why should constructor of Go return address? If we have this type:

    type My int
    
    func (m *My) Str() string { return strconv.Itoa(int(*m)) }
    

    This gives the compile-time error in question:

    m := map[int]My{0: My(12)}
    m[0].Str() // Error!
    

    But this works:

    m := map[int]*My{}
    my := My(12)
    m[0] = &my // Store a pointer in the map
    
    m[0].Str() // You can call it, no need to take the address of m[0]
               // as it is already a pointer
    

    Another option is to assign it to a local variable whose address can be taken, and call the pointer method on that. Care must be taken though, as if the method has pointer receiver, it might modify pointed object or its components (e.g. fields of a struct), which would not be reflected in the value stored in the map. If you go down this path, you might have to reassign the value to the key in the map to have the updated value.

    All-in-all, if you have a value whose type has methods with pointer receiver, you're better off using it (store, pass) as a pointer and not as a non-pointer value.

    See related questions:

    Pointer methods on non pointer types

    How can I store reference to the result of an operation in Go?

提交回复
热议问题