Interfaces

Duration: 20 min  •  Difficulty: Hard

An Interface is a contract. It defines "what can be done" by an object, regardless of "what that object is".

Concept

If a Struct has the methods required by an Interface, then that Struct is considered to implement that Interface automatically (Implicit Implementation).

Example Case

We have a Geometry interface that requires an area() method. Both Square and Circle have different area formulas, but both have an area() method. Therefore, both are Geometry.

MAIN.GO
package main
import (
"fmt"
"math"
)
// Contract: Anyone who has area() is Geometry
type Geometry interface {
area() float64
}
type Square struct {
side float64
}
type Circle struct {
radius float64
}
// Square follows the contract
func (s Square) area() float64 {
return s.side * s.side
}
// Circle follows the contract
func (c Circle) area() float64 {
return math.Pi * c.radius * c.radius
}
// This function receives Geometry (could be Square or Circle)
func printArea(g Geometry) {
fmt.Println("Area:", g.area())
}
func main() {
square := Square{side: 5}
circle := Circle{radius: 7}
// Polymorphism: One function can accept different types
printArea(square)
printArea(circle)
}