1

I don't understand why interface composition doesn't " inherit" the methods from the parent interface when it is satisfied in the implementation.

package main

import (
    "fmt"
)

type TestRepository interface {
    FindById(int) (error)
}

type TestService interface {
    TestRepository
    Method(id int) error
}



type testService struct {
    implRepository TestRepository
}

func NewTestService(r TestRepository) TestService {
    return &testService{implRepository: r}
}

When compiling this code i'm getting : *testService does not implement TestService (missing FindById method) while i'm actually expecting it to implement it since the type of "implRepository" is TestRepository.

It works if i do :

func NewTestService(r TestRepository) *testService {
    return &testService{implRepository: r}
}

But it kind of defeat the purpose of the interface ( as far as the service one goes at least )

What am i missing / how should it be done ?

0

1 Answer 1

1

The answer to your question is simply "you aren't composing the interface the way you need to." You have made TestRepository a struct member - that is not going to "inherit" the methods on that interface. What you need is the following:

type testService struct {
    TestRepository
}

func NewTestService(r TestRepository) TestService {
    return &testService{TestRepository: r}
}

Of course, the struct testService still need to implement Method(id int) error to actually work.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.