Interface Basics
Defining an Interface
An interface type lists a set of method signatures. It doesn't provide any implementation itself -- it's purely a contract describing what a type must be able to do.
Example: Defining an Interface
package main
import "fmt"
type Shape interface {
Area() float64
}
type Circle struct {
Radius float64
}
func (c Circle) Area() float64 {
return 3.14159 * c.Radius * c.Radius
}
func main() {
var s Shape = Circle{Radius: 2}
fmt.Println(s.Area())
}
Login to try C/C++/Java/PHP code in the editor
Implicit Satisfaction
Unlike languages where a type must explicitly declare which interfaces it implements, Go decides automatically: if a type has methods matching an interface's signatures, it satisfies that interface, with no declaration needed.
Note: This implicit design means you can define an interface that existing, unmodified types already satisfy.
Example: Implicit Satisfaction
package main
import "fmt"
type Greeter interface {
Greet() string
}
type English struct{}
func (English) Greet() string { return "Hello" }
type Spanish struct{}
func (Spanish) Greet() string { return "Hola" }
func main() {
greeters := []Greeter{English{}, Spanish{}}
for _, g := range greeters {
fmt.Println(g.Greet())
}
}
Login to try C/C++/Java/PHP code in the editor
Why Small Interfaces Win
Because satisfying an interface only requires having the right methods, small interfaces (often a single method) are easy for many different types to satisfy, making code more flexible and reusable -- this is why io.Reader and io.Writer, each with one method, are so central to Go's standard library.
Example: Why Small Interfaces Win
package main
import "fmt"
type Stringer interface {
String() string
}
type Money int
func (m Money) String() string {
return fmt.Sprintf("$%d", m)
}
func main() {
var s Stringer = Money(50)
fmt.Println(s.String())
}
Login to try C/C++/Java/PHP code in the editor
- Expecting to explicitly declare 'implements InterfaceName' like Java -- Go interfaces are satisfied implicitly by matching methods.
- Defining an interface with too many methods, making it hard for types to satisfy -- idiomatic Go favors small, focused interfaces.
- Assuming an interface value with a concrete type set is directly comparable to that concrete value with == in every case, without considering nil interface subtleties.
- An interface defines a set of method signatures a type must implement to satisfy it.
- Go interfaces are satisfied implicitly -- there's no implements keyword.
- Any type with the right methods automatically satisfies an interface, even ones you didn't write.
- Idiomatic Go favors small interfaces, often with just one or two methods.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: