Search code examples
gointerfacelanguage-designimplements

Golang inferred interfaces


Just a simple language design related question here. In languages like Swift, in order for a struct/class to conform to a protocol/interface, one needs to explicitly declare it as such

struct Dog: Animal {
    // implementation of Animal protocols here
}

But why is it that in Go, there are no explicit ways to show what interfaces a struct conforms to?

Isn't this just making things unclear or are there any other reasons behind it?


Solution

  • This allow to evolve to provide interface even for legacy types (which never explicitly declared respecting said interface)

    If those types already provide the right methods (ie the same API as the one specified by your interface), they will satisfy that interface.

    That allows to maintain a low coupling between those legacy types (which have no idea your interface exist) and your program, which accepts instances of that interface.

    See "What are some examples of Go interfaces?"

    Go's interfaces aren't a variant on Java or C# interfaces, they're much more.
    They are a key to large-scale programming and adaptable, evolutionary design.

    "It's the fact that I don't have to spend time up front designing some sort of type hierarchy and then rearranging it two or three times before I finish.
    It's not even the fact that it's easy to do it right -
    it's the fact that I just don't have to worry about it and can get on with the actual algorithm."

    Those quotes are from this 2012 article, and also from this thread, where you can read Rob Pike's comment:

    "It's always bothered me in OO languages that we can make Circle, Square, etc. subclasses of Shape (say), but that's the one design decision we get to make.
    What if we want to align those things along other axes (so to speak), like topological genus or plant genus, if you're a landscaper? You might lose your way or dig yourself into a hole with multiple inheritance."