如果通过golang中的接口字段类型,如何访问基础结构字段值?
如何通过接口获取结构字段值,是否有一些技巧(不可能直接)?
我在文件中有一个接口./ animals/mammal.go:
type Mammal interface {
Sound()
}
我在同一文件中实现了:
type Dog struct {
Name string
Age int
}
func (d *Dog) Sound {
fmt.Println("Say my name...", d.Name)
}
在其他软件包../../police/animals.go中,我有另一个结构:
type Policeman struct {
Animal Mammal
Policeman Name
ID int
}
我希望能够实现这样:
func (p *Policeman) Arrest {
fmt.Println("Hands up, police! Bite him, ", p.Animal.Name)
}
编译器不会让我这样做,因为p.animal是接口类型,当然是... 但是,是否有应用程序设计技巧/模式可以使我这样做。我的意思是,一旦我写了警察结构,我希望确定,当我将动物从狗变成猫或其他人时,我不会重写“逮捕”方法,所以这就是问题的重点!
Is there some trick (it is impossible directly) on how to get struct field values via interface?
I have an interface in a file ./animals/mammal.go:
type Mammal interface {
Sound()
}
I have implementation in the same file:
type Dog struct {
Name string
Age int
}
func (d *Dog) Sound {
fmt.Println("Say my name...", d.Name)
}
In other package ../../police/animals.go I have another struct:
type Policeman struct {
Animal Mammal
Policeman Name
ID int
}
And I wish to be able to implement it like this:
func (p *Policeman) Arrest {
fmt.Println("Hands up, police! Bite him, ", p.Animal.Name)
}
And compiler won't let me do that, because p.Animal is an interface type, of course...
However, is there an application design trick/pattern, that could allow me to do that. My point is, that once I wrote Policeman struct, I wish to be sure, that WHEN I CHANGE an animal from Dog to Cat or somebody else, I won't rewrite the "Arrest" method, so that's the point of the question!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果在您的上下文中,以下语句为真“所有哺乳动物都有一个名称”,则可以将方法
name()
添加到接口哺乳动物
,您的示例将有效这样:如果语句不正确,那么想要您想要的是不可能的,因为对于没有名称的哺乳动物的
name()
来调用该怎么办。请注意,您还需要实现
name()
dog> dog
。的方法If, in your context, the following statement is true "All mammals have a name", you can add a method
Name()
to the interfaceMammal
and your example would work like this:If the statement is not true, then want you want is impossible because it remains unclear what to do with a call to
Name()
for a mammal that does not have a name.Note that you then also need to implement the
Name()
method forDog
.