Saurav Kumar Singh
Saurav Kumar Singh

Reputation: 1478

Interface and Implementation

In following code snippet -

type Input interface {
    Name() string
}

type Abc interface {
    Do(Input)
}

type InputImpl struct {
}

func (InputImpl) Name() string {
    return "sample-impl"
}

type AbcImpl struct {
}

func (abcImpl *AbcImpl) Do(input Input){
    // do something
}

AbcImpl struct is an implementation of Abc interface, but changing last function like this -

func (abcImpl *AbcImpl) Do(input InputImpl){
    // do something
}

Now the AbcImpl is not implementing Abc anymore, though InputImpl is implementing Input interface !

Am I missing something or it's compulsory to have exact same signature (not event Impls) as the interface to be a legitimate implementation?

Upvotes: 2

Views: 103

Answers (2)

Trần Xuân Huy
Trần Xuân Huy

Reputation: 465

Yes, you do have to follow the method signature you specified. If you don't follow the signature, it will not be called "implementing".

an example: interface example

from tour of Go: There is no explicit declaration of intent, no "implements" keyword.


Upvotes: 5

Seaskyways
Seaskyways

Reputation: 3795

It is compulsory to use the very exact same signature when implementing an interface in Go. You can't implement it otherwise.

Upvotes: 1

Related Questions