Interface implementation in Go is implicit

I’m quite familiar with the concept of interface in Java; but on my first day reading my colleague’s Go code, I was a little confused. Here’s how:

In Java, implementing an interface is explicitly declared with the keyword implements, followed by the names of the interfaces being implemented. For example:

class PrivateLimitedCompany implements Business {
    @Override
    public String getUniqueEntityNumber() {
        // ...
    }

    @Override
    public String getBusinessName() {
        // ...
    }
}

By looking at the class header, it is very straightforward to see what interfaces the class implements.

In fact, in most Java IDEs, as long as the interface names are present after the implements keyword, the project won’t compile unless all the methods required by the interface are properly implemented.

However in Go, the implementation of an interface is implicit!

What this means is that you can’t tell if a class (I mean struct) implements any interface just by reading its definition.

Try this:

type PrivateLimitedCompany struct {
    // ...
}

func (c PrivateLimitedCompany) UniqueEntityNumber() string {
    // ...
}

func (c PrivateLimitedCompany) BusinessName() string {
    // ...
}

Nope. From this snippet alone, you can’t tell if PrivateLimitedCompany has anything to do with an interface called Business.

But if hypothetically somewhere in the project, there’s an interface that requires exactly two methods UniqueEntityNumber() and BusinessName() with the same parameter signature and output, e.g. like this:

type Business interface {
	UniqueEntityNumber() string
	BusinessName() string
}

Then PrivateLimitedCompany will qualify as an implementation of of the Business interface.

Until we actually try to use PrivateLimitedCompany as a Business, Go IDEs has no idea about the relations between the two. PrivateLimitedCompany on its own, still functions normally even without implementing any or all of the required methods.

Cool but…

Nothing wrong really, except something feels weird to me.

And I’m not the only one: See this reddit post.

Links:

Leave a Reply