如果通过golang中的接口字段类型,如何访问基础结构字段值?

发布于 2025-01-25 16:11:41 字数 716 浏览 4 评论 0原文

如何通过接口获取结构字段值,是否有一些技巧(不可能直接)?

我在文件中有一个接口./ 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

丿*梦醉红颜 2025-02-01 16:11:41

如果在您的上下文中,以下语句为真“所有哺乳动物都有一个名称”,则可以将方法name()添加到接口哺乳动物,您的示例将有效这样:

type Mammal interface {
     Sound()
     Name() string
}

func (p *Policeman) Arrest {
     fmt.Println("Hands up, police! Bite him, ", p.Animal.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 interface Mammal and your example would work like this:

type Mammal interface {
     Sound()
     Name() string
}

func (p *Policeman) Arrest {
     fmt.Println("Hands up, police! Bite him, ", p.Animal.Name())
}

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 for Dog.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文