Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you explain Go Interfaces?

Tags:

go

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.

like image 208
Sri Kadimisetty Avatar asked Oct 11 '11 05:10

Sri Kadimisetty


People also ask

What are Go interfaces?

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.

What are interfaces used for in Go?

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.

Are Go interfaces like classes?

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.


2 Answers

This is a pretty good overview:

http://research.swtch.com/2009/12/go-data-structures-interfaces.html

like image 90
ctcherry Avatar answered Oct 05 '22 18:10

ctcherry


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.

like image 22
Dustin Avatar answered Oct 05 '22 18:10

Dustin