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

huangapple go评论97阅读模式
英文:

Why do structs with an anonymous struct field not satisfy methods defined on an alias of that type?

问题

我有一个在我的包之外定义的结构体,我想给它附加一个方法。由于包正在反射原始类型,我不能在结构体中使用别名,而必须使用原始类型。下面是我尝试做的事情的实质:

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()
}

尝试编译这段代码会导致错误信息 type *Player has no field or method PrintLocation。如果我在 Entity 上定义 PrintLocation() 方法,它就可以工作。如果 AliasEntity 是完全相同的东西,为什么编译器会报错呢?

英文:

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?

答案1

得分: 5

那不是一个别名。byteuint8是别名,但你创建的是一个新类型Alias,其底层类型是Entity

不同的类型有自己的一套方法,并不从底层类型继承。

所以Entity没有任何方法,而Alias有一个名为PrintLocation()的方法。

英文:

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().

答案2

得分: 1

这里有几个问题:

1 - new(Player) 返回一个指向新分配的类型为 Player 的零值的指针。
http://golang.org/doc/effective_go.html#allocation_new

你应该使用 Player{}

2 - PrintLocation 方法的接收者是 Alias,与 EntityPlayer 没有关系。

英文:

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.

huangapple
  • 本文由 发表于 2014年4月29日 08:37:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/23353548.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定