Cannot take the address of map element

前端 未结 2 1149
旧巷少年郎
旧巷少年郎 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条回答
  •  孤城傲影
    2021-01-29 06:16

    @icza's answer is the correct one.

    Here is an example to illustrate how "value receiver" vs "pointer receiver" interact with "pointer map" vs "values map" :

    https://play.golang.org/p/JVp6DirgPkU

    package main
    
    import (
        "fmt"
    )
    
    // a simple type, with two methods : one with a value receiver, one with a pointer receiver
    type Item struct {
        name string
    }
    
    func (i Item) GetNameByValue() string {
        return i.name
    }
    
    func (i *Item) GetNameByRef() string {
        return i.name
    }
    
    func main() {
        {
            // in this map, we store *pointers* to Item values
            mapByRef := make(map[int]*Item)
    
            mapByRef[0] = &Item{"I am stored as a pointer"}
    
            // GetNameByRef will work on a *Item : "mapByRef[0]" is already a pointer
            fmt.Println("GetByRef   :", mapByRef[0].GetNameByRef())
    
            // GetNameByValue will work on a *Item :   go automatically turns this into '(*mapByRef[0]).GetNameByValue()', and this is valid
            fmt.Println("GetByValue :", mapByRef[0].GetNameByValue())
        }
    
        {
            // in this map, we store Item values (no pointers)
            mapByValue := make(map[int]Item)
    
            mapByValue[0] = Item{"I am stored as a value"}
    
            // GetNameByValue will work on a Item :  "mapByValue[0]" has the right type
            fmt.Println("GetByValue :", mapByValue[0].GetNameByValue())
    
            // GetNameByRef will not work :  go tries to turn this into :  (&mapByValue[0]).GetNameByRef(),
            // and go refuses to let you take the address of a value inside a map
    
            // fmt.Println("GetByRef   :", mapByValue[0].GetNameByRef())
    
            // compiler error :
            //   ./prog.go:47:46: cannot call pointer method on mapByValue[0]
            //   ./prog.go:47:46: cannot take the address of mapByValue[0]
    
            // you will need some way to copy the value before taking its address :
            item := mapByValue[0]
            fmt.Println("item.GetByRef    :", item.GetNameByRef())
            // same as :
            fmt.Println("(&item).GetByRef :", (&item).GetNameByRef())
        }
    }
    
    // Output :
    //
    // GetByRef   : I am stored as a pointer
    // GetByValue : I am stored as a pointer
    // GetByValue : I am stored as a value
    // item.GetByRef    : I am stored as a value
    // (&item).GetByRef : I am stored as a value
    

提交回复
热议问题