I have a struct defined outside my package that I would like to attach a method to. Due to the fact that the package is reflecting on the original type, I cannot use the alias within my struct, I have to use the original type. Below is essentially what I'm trying to do:
package main
import "fmt"
type Entity struct {
loc_x int
loc_y int
}
type Player struct {
Entity
name string
}
type Alias Entity
func (e Alias) PrintLocation() {
fmt.Printf("(%v, %v)", e.loc_x, e.loc_y)
}
func main() {
player := new(Player)
player.PrintLocation()
}
Attempting to compile this results in type *Player has no field or method PrintLocation
. If I define the PrintLocation()
method on Entity
, it works. If Alias
and Entity
are the same exact thing, why is the compiler complaining?
That is not an alias. byte
and uint8
are aliases, but what you have created is a new type ,Alias
, with the underlying type of Entity
.
Different types have their own set of methods and doesn't inherit them from the underlying type.
So Entity
has no methods at all, and Alias
has the method of PrintLocation()
.
There're a few things that are wrong here:
1 - new(Player)
returns a pointer to a newly allocated zero value of type Player
http://golang.org/doc/effective_go.html#allocation_new
You should use Player{}
instead.
2 - The receiver of your PrintLocation
method is Alias
, which has nothing to do with Entity
or Player
.