ThePiachu
ThePiachu

Reputation: 9175

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

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?

Upvotes: 0

Views: 189

Answers (1)

evanmcdonnal
evanmcdonnal

Reputation: 48076

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.

Upvotes: 1

Related Questions