Go Interfaces Explained with Examples

Updated 4 min read
Go Interfaces featured image: cards showing an interface, a type assertion and a type switch

Go interfaces let different types share the same behaviour, so one function can work with all of them. In this post, you will learn to define interfaces, satisfy them and check what type sits inside one. Each idea comes with a short example that you can run yourself.

Interfaces are built on methods, so first make sure you are comfortable with structs and methods in Go. Pointer receivers also matter here, which you learned in pointers in Go, copy vs share.

What Are Go Interfaces?

An interface is a list of method names. Then any type that has all those methods automatically fits the interface. In other words, an interface describes what a type can do, not what it is.

Think of a phone charger port. The charger does not care which brand of phone you plug in. It only cares that the phone has the right port. Similarly, Go interfaces only care that a type has the right methods.

Defining and Using Go Interfaces

type Shape interface {
	Area() float64
}

type Rectangle struct{ Width, Height float64 }
type Circle struct{ Radius float64 }

func (r Rectangle) Area() float64 { return r.Width * r.Height }
func (c Circle) Area() float64    { return math.Pi * c.Radius * c.Radius }

The Shape interface asks for one method, Area, which returns a float64. Also, both Rectangle and Circle have that method. So both of them are Shapes, even though they hold very different fields.

Implicit Implementation

Notice that we never wrote “Rectangle implements Shape”. Unlike Java, Go has no implements keyword. Instead, a type satisfies an interface just by having the methods, which keeps your code loosely connected.

One Function, Many Types

func printArea(s Shape) {
	fmt.Printf("%.2f\n", s.Area())
}

printArea(Rectangle{Width: 3, Height: 4}) // 12.00
printArea(Circle{Radius: 1})              // 3.14

In short, the function accepts any Shape. Then, at run time, Go calls the right Area method for each type. The diagram below shows this flow.

Go Interfaces diagram showing Rectangle and Circle both satisfying the Shape interface

Rectangle and Circle both have Area(), so printArea accepts either one as a Shape.

A Slice of Go Interfaces

shapes := []Shape{Rectangle{2, 5}, Circle{2}}

total := 0.0
for _, s := range shapes {
	total += s.Area()
}
fmt.Printf("Total: %.2f\n", total) // Total: 22.57

A slice of Go interfaces can hold many different types at once. As a result, one loop handles them all. This is how real programs treat payment methods, file stores or notification channels in the same way.

The Empty Interface: any

An interface with no methods is satisfied by every type. Go names it any, and it is how fmt.Println accepts all kinds of values. However, you lose type safety with it, so use it only when you must.

Type Assertions

var s Shape = Circle{Radius: 3}

if c, ok := s.(Circle); ok {
	fmt.Println("Radius:", c.Radius) // Radius: 3
}

A type assertion asks, “Is the value inside really a Circle?” The comma ok form returns false instead of crashing when the answer is no.

Type Switches

func describe(v any) {
	switch t := v.(type) {
	case int:
		fmt.Println("int:", t)
	case string:
		fmt.Println("string:", t)
	default:
		fmt.Println("other")
	}
}

describe(42)   // int: 42
describe("hi") // string: hi
describe(3.5)  // other

Similarly, a type switch checks several types in one go. It works just like the switch you learned earlier, only it compares types instead of values.

Go Interfaces in the Standard Library

type Dog struct{}

func (d Dog) String() string { return "Dog says woof" }

fmt.Println(Dog{}) // Dog says woof

The fmt package looks for a String() method, which is the fmt.Stringer interface. For example, other famous ones are error and io.Reader. In fact, small interfaces with one or two methods are the Go way.

Common Mistakes with Go Interfaces

Error you seeWhy it happensHow to fix it
Square does not implement Shape (missing method Area)The type lacks a method.Add the missing method.
Rect does not implement Shape (method Area has pointer receiver)Only *Rect has the method.Pass &Rect{} instead.
panic: interface conversion: main.Shape is main.Circle, not main.RectA plain assertion guessed the wrong type.Use the comma ok form.

In particular, the pointer receiver error confuses many beginners. Interviewers love it too, so try my Go interview questions and answers next.

Official Resources

These pages come straight from the Go team, so they are always accurate and up to date.

Quick Recap

  • Go interfaces list methods, and any type with those methods fits.
  • There is no implements keyword, because matching is automatic.
  • One function or slice can work with many types through an interface.
  • Use v.(Type) with ok, or a type switch, to find the real type.
  • Keep interfaces small, like Stringer and error.

What’s Next?

You just met the error interface. Next, we will use it properly and learn how Go handles errors without exceptions.

Coming soon: Go Error Handling Explained for Beginners