I have a simple struct and receiver. I try to set the map with the struct and then call the receiver.
Like that:
package main
import (
"fmt"
)
type myStruct struct {
FirstName string
LastName string
}
func (m *myStruct) GetFirstName() string {
return m.FirstName
}
func (m *myStruct) GetLastName() string {
return m.LastName
}
func main() {
testMyStruct := myStruct {
FirstName: "x1",
LastName: "x2",
}
myMapStruct["test2"] = testMyStruct
fmt.Println(myMapStruct["test2"].GetFirstName())
}
I'm getting this error:
cannot call pointer method getFirstName on myStruct
Why can I call the receiver method from the map?
x.M(), wherexis of typeTandMis a method of*T, is shorthand for(&x).M(). However, for(&x).M()to be validxMUST be addressable. A map index expression, e.g.m[k], is NOT addressable. Thereforem[k].M()is illegal ifm[k]is of typeTandMis a method of*T. One of the reasons whym[k]is not addressable is that "growing a map might cause rehashing of existing elements into new storage location, thus potentially invalidating the address" (from The Go Programming Language book).