Reputation: 14919
I have read through most of the Go tour tutorial, but I'm still unclear on how Go's interface programming model compares with OOP?
Can someone explain how I can start 'thinking in Go'?
I'm confused how you can define an interface, and then create objects based on the interface?
Does Go implicitly create an concrete implementation for you during compile time?
Upvotes: 1
Views: 186
Reputation: 42429
Traditional (Java) OO is about class hierarchies. You model your problem with classes, some abstract, some final and interfaces. Then you provide implementations.
Go lets you go the other way around: Start with concrete types and implement your logic. If a useful abstraction emerges or is required: Pack it into an interface and refactor your code to use this interface type.
Upvotes: 0
Reputation: 8898
Go's interface system is akin to structural typing. Consider a snippet of python code:
def foo(bar):
bar.baz(5)
In this snippet we don't know what concrete type bar
is but we can say that it must have a baz
method which accepts a single int
argument. Note that when we're writing the class of bar
we don't have to declare that we're implementing this 'interface' (having a baz
method which takes an integer). We just write a baz
method which works correctly when called with a single int
and we can pass an instance to the foo
method.
Go works in a similar manner but everything is checked at compile time. In Python if we pass our foo
method an instance of a class which does not have a baz
method we get a runtime exception. In Go we would define an interface with the baz
method and state in the type of foo
that it takes an instance of that interface. Now any type which has a baz
method on a single int
satisfies the type that foo
requires.
Upvotes: 2
Reputation: 25245
One of the problems OOP usually tries to solve is Polymorphism or the the ability for two different classes to have instances that behave the same. Usually in OOP this is accomplished by using inheritance. A Base class defines a minimal interface that other classes extend. All of the subclasses of Base class can be used as a Base class.
Go does the same thing not by inheritance but using interfaces. An interface is a "description" of behaviour. It is up to the individual Types in Go to satisfy this description by implementing each of the methods described in the interface. If a Type does implement all the methods described in the interface then it automatically satisfies the interface and can be cast to that interface automatically by the compiler.
Upvotes: 2