You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Interfaces are one of Go's most powerful features. Unlike Java or C#, Go interfaces are satisfied implicitly — a type implements an interface simply by having the right methods. There is no implements keyword. This design enables flexible, decoupled code.
An interface specifies a set of method signatures:
type Shape interface {
Area() float64
Perimeter() float64
}
Any type that has Area() float64 and Perimeter() float64 methods automatically satisfies the Shape interface.
type Circle struct {
Radius float64
}
func (c Circle) Area() float64 {
return math.Pi * c.Radius * c.Radius
}
func (c Circle) Perimeter() float64 {
return 2 * math.Pi * c.Radius
}
type Rectangle struct {
Width, Height float64
}
func (r Rectangle) Area() float64 {
return r.Width * r.Height
}
func (r Rectangle) Perimeter() float64 {
return 2 * (r.Width + r.Height)
}
Both Circle and Rectangle implement Shape implicitly:
func printShape(s Shape) {
fmt.Printf("Area: %.2f, Perimeter: %.2f\n", s.Area(), s.Perimeter())
}
printShape(Circle{Radius: 5})
printShape(Rectangle{Width: 4, Height: 6})
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.