为什么具有匿名struct字段的结构不满足在该类型的别名上定义的方法?

w.b*_*ian 2 go

我有一个在我的包外面定义的结构,我想附加一个方法.由于包是反映原始类型的事实,我不能在我的结构中使用别名,我必须使用原始类型.以下基本上是我想要做的:

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()
}
Run Code Online (Sandbox Code Playgroud)

试图编译这会导致type *Player has no field or method PrintLocation.如果我定义了PrintLocation()方法Entity,它就可以了.如果Alias并且Entity是完全相同的,为什么编译器会抱怨?

ANi*_*sus 5

那不是别名.byte并且uint8是别名,但您创建的是一个新类型,Alias其基础类型为Entity.

不同类型具有自己的一组方法,并且不从基础类型继承它们.

所以Entity没有任何方法,并且Alias有方法PrintLocation().