在Go语言中,是可以同时指定具有变量的结构体和接口的。

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

Is it possible to specify both a structure with variables and an interface at the same time in golang?

问题

我目前正在清理一些 Golang 代码。这段代码涉及到许多行为类似且共享一些相似数据字段的结构体。我想知道是否可以同时指定一个公共的结构体和接口?类似这样:

type Foo struct {
    Bar string
    BarTheFoo() string
}

func (f Foo) FooBar() string {
    BarTheFoo()
    return f.Bar
}

这意味着从 Foo 继承的任何其他结构体都会有 Bar 变量,并且还应该实现自己的 BarTheFoo() 函数。我知道所有的 Foo 派生结构体都会有 BarTheFoo(),我想在一个函数中使用它,我知道这个函数对于每个 Foo 派生结构体来说都是相同的。

在 Go 中是否可以实现这样的功能?

英文:

I'm currently working on cleaning up some golang code. The code deals with a lot of structures that behave in a similar fashion and share some similar data fields. I'm wondering whether it's possible to specify a common structure and interface at the same time? Something like:

type Foo struct {
	Bar string
	BarTheFoo() string
}

func (f Foo)FooBar() string {
	BarTheFoo()
	return f.Bar
}

Meaning that any other structure inheriting from Foo will have the Bar variable in it, but that it should also implement its own BarTheFoo() function. Knowing that all the Foo derivatives will have BarTheFoo(), I would like to use it in a function I know will look the same for every Foo derivative.

Is something like this possible in Go?

答案1

得分: 1

是的,但为了完全理解它,我认为你需要摒弃那些关于继承的概念,因为在Go语言中它们并不存在。你可以在所有类型(包括Foo)中"嵌入" Bar 来实现最接近的效果。

这个特性有点像继承和组合的混合体。虽然 Foo 类型在技术上是由 Bar 类型(以及其他字段)"组合"而成的,但 Bar 类型上的方法在某种意义上被提升,以便可以直接从 Foo 中调用。代码如下:

type Foo struct {
    Bar
}

type Bar struct {
    // 假设这个类型是有用的
}

func (b Bar) FooBar() string {
    // 假设这个方法是有用的
    return b.ThatProperty
}

然后在其他上下文中,你可以这样做:

f := &Foo{}
f.Bar()

我不确定这是否完全符合你的需求,如果需要更多指导,我可以进行编辑。但是,我无法具体回答你的问题,因为你所问的在Go语言中并不存在。

英文:

Yeah but in order to understand it fully I think you'll need to depart from those notions of inheritance as they don't exist in Go. The nearest thing you can do is 'embed' Bar in all your types (Foo included).

This feature acts somewhat like a blend of inheritance and composition. While the Foo type will technically be 'composed' of a Bar type (among other fields), the methods on the Bar type are in a sense promoted so that they can be invoked directly from Foo. It looks like this;

type Foo struct {
    Bar
}

type Bar struct {
    // pretend this type is useful
}

func (b Bar)FooBar() string {
    // pretend this is useful
    return b.ThatProperty
}

Then in some other context you can do;

f := &Foo{}
f.Bar()

I'm not sure that is exactly what you want to do and I can edit with more guidance however I can't answer your question specifically because what you're asking doesn't exist in Go.

huangapple
  • 本文由 发表于 2015年7月16日 07:17:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/31442849.html
匿名

发表评论

匿名网友

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

确定