Interfaces
What you will learn
An interface lets you write code that works with anything that has the right behaviour, without caring what the thing actually is. This lesson shows how interfaces are declared and satisfied (implicitly, which is unusual), why small interfaces are best, how pointer receivers affect them, how to recover the concrete type with type assertions, and one famous trap with nil.
The problem interfaces solve
Imagine you want a function that prints a shape's area. Without interfaces, you need one function per shape:
func printRectangleArea(r Rectangle) { ... }
func printCircleArea(c Circle) { ... }
The logic is identical. All it really needs is "something that can report an area". An interface expresses exactly that.
Declaring an interface
An interface is a list of methods:
type Shape interface {
Area() float64
}
Any type that has a method Area() float64 is a Shape. You never write "implements". This is called implicit satisfaction:
type Rectangle struct {
Width, Height float64
}
func (r Rectangle) Area() float64 {
return r.Width * r.Height
}
type Circle struct {
Radius float64
}
func (c Circle) Area() float64 {
return math.Pi * c.Radius * c.Radius
}
Neither type mentions Shape. Now one function handles both:
func describe(s Shape) {
fmt.Printf("area: %.2f\n", s.Area())
}
func main() {
describe(Rectangle{Width: 3, Height: 4}) // area: 12.00
describe(Circle{Radius: 1}) // area: 3.14
}
The compiler checks that a type has the required methods at the place you use it. If a type is missing one, you get an error like Square does not implement Shape (missing method Area).
Why implicit is useful
Because satisfaction is automatic, you can define an interface after the types exist, and even for types in other packages that you did not write. The package that uses the behaviour defines the interface it needs, and the package that provides the type does not need to know about it. This keeps packages loosely connected.
Interfaces are especially valuable at boundaries:
- A function reads bytes but does not care whether they come from a file, a network connection, or a string.
- Business logic saves data but should not depend on one specific database.
- A test needs a small fake instead of the real thing.
Keep interfaces small
The most useful interfaces have one or two methods. The standard library's io.Reader has a single method:
type Reader interface {
Read(p []byte) (n int, err error)
}
Files, network connections, compressed streams, HTTP request bodies, and in-memory buffers all satisfy it, so thousands of functions accept any of them. Another example is fmt.Stringer, a one-method interface that lets a type control how it prints:
type Stringer interface {
String() string
}
Interface values
A variable of an interface type holds two things: the concrete type stored inside it and the value of that type. You can put different concrete types in a slice of interface values:
shapes := []Shape{
Rectangle{Width: 3, Height: 4},
Circle{Radius: 1},
}
total := 0.0
for _, s := range shapes {
total += s.Area()
}
fmt.Printf("total area: %.2f\n", total) // total area: 15.14
Each call to s.Area() runs the method of whichever concrete type is inside.
Pointer receivers and interfaces
If a method has a pointer receiver, only a pointer to the type satisfies the interface:
type Counter struct{ Value int }
func (c *Counter) Increment() { c.Value++ }
type Incrementer interface {
Increment()
}
var a Incrementer = &Counter{} // valid
var b Incrementer = Counter{} // compile error
cannot use Counter{} (value of type Counter) as Incrementer value in variable declaration: Counter does not implement Incrementer (method Increment has pointer receiver)
The reason is that a plain value stored in an interface is not addressable, so Go cannot take its address to call the method. This is also why the previous lesson advised keeping all of a type's receivers consistent.
The empty interface
An interface with no methods is satisfied by every type. It is written any:
var anything any
anything = 42
anything = "hello"
anything = []int{1, 2, 3}
any is occasionally necessary, as with fmt.Println, which accepts values of any type. But it tells the compiler nothing, so you lose type checking. Prefer a specific interface whenever you can.
Type assertions and type switches
Sometimes you need the concrete value back out of an interface. A type assertion does that:
var s Shape = Circle{Radius: 2}
circle, ok := s.(Circle)
if ok {
fmt.Println("radius:", circle.Radius)
}
Always use the two-value form with ok. Without it, a failed assertion panics. To handle several possible types, use a type switch:
func describeValue(input any) {
switch v := input.(type) {
case string:
fmt.Println("string of length", len(v))
case int:
fmt.Println("int:", v)
case Shape:
fmt.Printf("shape with area %.2f\n", v.Area())
default:
fmt.Println("unknown type")
}
}
Inside each case, v has that case's type. If you find yourself writing many type switches, a better interface is often the cleaner design.
The nil-interface trap
An interface value is nil only when it has no concrete type and no value. A nil pointer inside an interface is not a nil interface:
type MyError struct{}
func (e *MyError) Error() string { return "my error" }
func mayFail() error {
var err *MyError = nil
return err // returns an error interface holding a nil *MyError
}
func main() {
err := mayFail()
fmt.Println(err == nil) // false!
}
The interface contains the type *MyError, even though the pointer is nil, so the comparison with nil is false. The safe habit: when there is no error or value, return a literal nil for the interface type, never a typed nil pointer.
Checking at compile time
To confirm a type satisfies an interface, without waiting for the place it is used, add this line:
var _ Shape = Circle{}
It assigns to the blank identifier, so it generates no code, but the compiler checks the assignment. It is a common safeguard in library code.
Common mistakes
- Making interfaces too large. A ten-method interface is hard to satisfy and hard to fake.
- Defining an interface next to the only type that implements it. Define it where it is consumed.
- Returning a typed nil pointer as an interface.
- Forgetting that pointer-receiver methods are not in the value's method set.
- Overusing
any. It removes the compiler's help.
Practice
Create a Shape interface with an Area() float64 method. Implement it for Rectangle and Circle. Write a function totalArea(shapes []Shape) float64 that sums their areas. Test it with a 3 by 4 rectangle and a circle of radius 1.
package main
import (
"fmt"
"math"
)
type Shape interface {
Area() float64
}
type Rectangle struct {
Width, Height float64
}
func (r Rectangle) Area() float64 {
return r.Width * r.Height
}
type Circle struct {
Radius float64
}
func (c Circle) Area() float64 {
return math.Pi * c.Radius * c.Radius
}
func totalArea(shapes []Shape) float64 {
total := 0.0
for _, s := range shapes {
total += s.Area()
}
return total
}
func main() {
shapes := []Shape{
Rectangle{Width: 3, Height: 4},
Circle{Radius: 1},
}
fmt.Printf("total area: %.2f\n", totalArea(shapes))
}
Output:
total area: 15.14
The rectangle contributes 12 and the circle about 3.14. totalArea never mentions Rectangle or Circle, so you could add a Triangle type with an Area method and use it with no changes to this function. Both types use value receivers, so plain values satisfy Shape.
Summary
An interface is a set of methods, and any type that has them satisfies it automatically, with no implements keyword. Small interfaces, defined by the code that uses them, give flexible and testable code. Pointer-receiver methods belong only to the pointer type, so only the pointer satisfies the interface. Use type assertions with ok or type switches to recover concrete types, and avoid the nil-interface trap by returning a plain nil when there is nothing to return.
Official reference: A Tour of Go: Interfaces and Effective Go: Interfaces.
Ready to wrap up?
Mark this complete when you can explain the main idea and finish the practice task.