Go does not explicitly say that a struct implements an interface. If a struct implements all the methods of an interface, it automatically becomes of the interface type. Thus, in Go, interfaces are implemented implicitly.
Therefore, in Go, an interface type is a set of method signatures. The best way to understand interfaces is to see it in action.
In the snippet above, we have defined
Shape to be an interface that provides the methods
perimeter(). Any struct that implements these two methods will become a
We then define two structs -
Triangle and implement the methods
perimeter() for each of them, allowing them to be a
We then define a function called
printProperties() which prints the area and perimeter of a
Shape provided as argument.
As you would see if you run this program, the method
printProperties() works on both
t which are of type
Side note: The above example actually depicts polymorphism - ability for instances to behave as other types. Check out more on polymorphism here.