S
S
Sergey Tikhonov2019-03-15 11:16:56
go
Sergey Tikhonov, 2019-03-15 11:16:56

How to make interface for type hierarchy?

There are two types in the project - "group" and "element". The group has a "get certain items" method. We get something like this:

type element struct {}

func (el *element) doA() int {...}
func (el *element) doB() int {...}

type group struct {
    elements []*element
}

func (g *group) getElements() []*element {...}

And there are two services, each of which uses elements of groups in its own way. The first of the elements needs only the doA method, the second - doB. The idea that never gets out of my head is: "why give services a complete implementation when you can limit yourself to the interfaces that the services themselves need?". For example, so that you can’t just take and call the doA method from service B.
Interfaces appear:
type AElement interface {doA() int}
type BElement interface {doB() int}

type AGroup interface {
    getElements() []AElement
}
type BGroup interface {
    getElements() []BElement
}

Well, "*group" does not satisfy either AGroup or BGroup, because getElements has different return types. A question for pattern and go connoisseurs: is this a completely crazy idea, or is there still a technical possibility to restrict service access to the element's functionality by an interface?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
nrgian, 2019-04-28
@nrgian

Check which interface is available, cast to it:

readyForUse, ok:= element.(AElement)
if ok {
     readyForUse.doA()
}

Sergei Tikhonov Sergei Tikhonov
Not types to cast, namely that interfaces.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question