Defining and Implementing Interfaces
Implicit satisfaction and the empty interface
What Is an Interface?
An interface in Go is a set of method signatures. Any type that implements all those methods implicitly satisfies the interface — no implements keyword needed. This is called structural typing or duck typing.
Declaring an Interface
Define an interface with the type keyword:
package main
import "fmt"
type Shape interface {
Area() float64
Perimeter() float64
}
type Circle struct{ Radius float64 }
func (c Circle) Area() float64 { return 3.14159 * c.Radius * c.Radius }
func (c Circle) Perimeter() float64 { return 2 * 3.14159 * c.Radius }
func main() {
var s Shape = Circle{5}
fmt.Printf("Area: %.2f\n", s.Area())
}All lessons in this course
- Defining and Implementing Interfaces
- Core Standard Library Interfaces
- Type Assertions and Type Switches
- Interface Composition and Best Practices