I dont get the whole types + Interfaces model(that replaces classes in other languages). If theres a simple way you could explain what they are about, it will be really appreciated.
In Go, an interface is a set of method signatures. When a type provides definition for all the methods in the interface, it is said to implement the interface. It is much similar to the OOP world. Interface specifies what methods a type should have and the type decides how to implement these methods.
Interfaces allow us to not repeat code. We can use interfaces to pass multiple structs into the same function where we want the same behavior.
The key principle of an interface in Go is to provide method signatures for similar types of objects. Go does not have classes and inheritance to implement object orientation.
This is a pretty good overview:
http://research.swtch.com/2009/12/go-data-structures-interfaces.html
Go interfaces are statically checked duck typing.
The difference between pure virtual classes in C++ or interfaces in java is that you don't declare the interface on the class that implements the interface, but on the method that receives the interface.
For example, I can create an interface with a Read
and a Write
method and call it ThingsDustinReadsAndWrites
and have a function called doReadsAndWrites(rr ThingsDustinReadsAndWrites
. That can, in turn, receive a built-in http.ClientConn
which has never heard of my interface, but implements it because it happens to have those methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With