英文:
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() 方法,它就可以工作。如果 Alias 和 Entity 是完全相同的东西,为什么编译器会报错呢?
英文:
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
那不是一个别名。byte和uint8是别名,但你创建的是一个新类型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,与 Entity 或 Player 没有关系。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论