Level: BeginnerGo Programs

Go Interface Programs: Shapes, Stringer, Type Switch and More

Updated 18 min read
Go Interface Programs featured image: shape area and payment output

Go interface programs let different types share behaviour, so one function can work with a circle, a rectangle or any shape you add later. Interfaces are how Go does polymorphism, and they power key parts of the standard library such as io.Writer, fmt.Stringer and error. In this post, you will write fourteen interface programs with their exact output, and then practice the interface questions that trip up many developers, including the famous nil interface trap.

You need structs and methods from our Go struct programs, and pointer receivers from our Go pointer programs. For the theory, read Go interfaces explained with examples. All programs were tested on Go 1.27.

What are Go Interface Programs?

Go interface programs define an interface, which is a list of method signatures. Any type that has all those methods automatically satisfies the interface. You never write “implements”, because Go checks it for you.

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. An interface is that port: any type with the right methods fits.

Why Go Interface Programs Matter

Interfaces let you write code that works with types that do not exist yet. For example, a payment service can accept any payment method, a logger can write to a file or the screen, and tests can swap a real database for a fake one.

  • Flexible code: one function works with many types.
  • Testing: pass a fake that satisfies the same interface.
  • Standard library: io.Reader, io.Writer, error and fmt.Stringer are all interfaces.
  • Interviews: nil interfaces, type assertions and pointer receivers are common questions.

How Go Interface Programs Work

An interface value holds two things: the concrete type and the value of that type. When you call a method on the interface, Go looks up the method for the stored type and calls it. If the type has every method in the interface, Go allows the assignment at compile time.

Go interface programs diagram showing Circle and Rectangle satisfying a Shape interface
Any type with an Area method satisfies Shape, so one function can work with every shape.

The table below lists the interface tools used in this post.

ToolSyntaxUse it for
Interface typetype Shape interface { Area() float64 }Define behaviour
SatisfyAdd the methods to your typeNo keyword needed
Type assertionc, ok := s.(Circle)Get the concrete type
Type switchswitch v := s.(type) { }Handle many types
Empty interfaceany (same as interface{})Hold any value
Embeddingtype ReadWriter interface { Reader; Writer }Combine interfaces
Compile checkvar _ Shape = Circle{}Prove a type fits

Basic Go Interface Programs

These first Go interface programs start with a tiny example and then build the classic shapes example.

Program 1: Your First Interface with Two Vehicles

Start here if Go interface programs are new to you. The interface has one method, and two simple types provide it.

package main

import "fmt"

// Vehicle is anything that can tell us how many wheels it has.
type Vehicle interface {
    Wheels() int
}

// Bike is one kind of vehicle.
type Bike struct{}

// Car is another kind of vehicle.
type Car struct{}

// Wheels makes Bike satisfy Vehicle.
func (bike Bike) Wheels() int { return 2 }

// Wheels makes Car satisfy Vehicle.
func (car Car) Wheels() int { return 4 }

// showWheels works with ANY Vehicle.
func showWheels(name string, vehicle Vehicle) {
    fmt.Println(name, "has", vehicle.Wheels(), "wheels")
}

func main() {
    showWheels("Bike", Bike{})
    showWheels("Car", Car{})
}
Bike has 2 wheels
Car has 4 wheels

Vehicle only asks for one method, Wheels() int. Both Bike and Car have that method, so both count as a Vehicle. Then showWheels can take either one without knowing which it got.

Program 2: Shape Interface with Area

This program uses the names from the diagram above: Shape, Circle, Rectangle and Area.

package main

import (
    "fmt"
    "math"
)

// Shape is any type that can work out its own area.
type Shape interface {
    Area() float64
}

// Rectangle has a width and a height.
type Rectangle struct{ Width, Height float64 }

// Circle has a radius.
type Circle struct{ Radius float64 }

// Area of a rectangle is width times height.
func (rectangle Rectangle) Area() float64 { return rectangle.Width * rectangle.Height }

// Area of a circle is pi times radius squared.
func (circle Circle) Area() float64 { return math.Pi * circle.Radius * circle.Radius }

// printArea accepts any Shape and prints its type and area.
func printArea(shape Shape) {
    fmt.Printf("%T area: %.2f\n", shape, shape.Area()) // %T prints the type name
}

func main() {
    printArea(Rectangle{4, 5})
    printArea(Circle{3})
}
main.Rectangle area: 20.00
main.Circle area: 28.27

printArea accepts any Shape. Both types satisfy it, because each one has an Area() float64 method. Inside, Go calls the right Area for the type you passed.

Program 3: A Slice of Interfaces

package main

import "fmt"

// Shape is any type with an Area method.
type Shape interface{ Area() float64 }

// Square has one side length.
type Square struct{ Side float64 }

// Triangle has a base and a height.
type Triangle struct{ Base, Height float64 }

func (square Square) Area() float64     { return square.Side * square.Side }
func (triangle Triangle) Area() float64 { return 0.5 * triangle.Base * triangle.Height }

func main() {
    shapes := []Shape{Square{3}, Triangle{4, 6}, Square{2}} // different types in one slice
    total := 0.0
    for _, shape := range shapes {
        total += shape.Area()
    }
    fmt.Println("Total area:", total)
}
Total area: 25

So the slice holds different types, but the loop treats them all the same way. It adds 9, 12 and 4 to get 25. Adding a new shape needs no change to this loop.

Program 4: Payment Methods

package main

import "fmt"

// Payer is anything that can pay an amount.
type Payer interface {
    Pay(amount float64) string
}

// UPI pays with a UPI ID.
type UPI struct{ ID string }

// Card pays with a card.
type Card struct{ Last4 string }

func (upi UPI) Pay(amount float64) string {
    return fmt.Sprintf("Paid %.2f via UPI %s", amount, upi.ID)
}

func (card Card) Pay(amount float64) string {
    return fmt.Sprintf("Paid %.2f via card ending %s", amount, card.Last4)
}

// checkout works with any Payer.
func checkout(payer Payer, total float64) {
    fmt.Println(payer.Pay(total))
}

func main() {
    checkout(UPI{"asha@bank"}, 499)
    checkout(Card{"4242"}, 1250.5)
}
Paid 499.00 via UPI asha@bank
Paid 1250.50 via card ending 4242

Each type has its own Pay method with its own message. As a result, checkout does not know or care how each method pays. Tomorrow you can add a Wallet type without touching checkout.

Standard Library Go Interface Programs

Go’s standard library is full of small interfaces. These Go interface programs use the most common ones.

Program 5: fmt.Stringer

package main

import "fmt"

// Temperature is a float64 with its own String method.
type Temperature float64

// String tells fmt how to print a Temperature.
func (temperature Temperature) String() string {
    return fmt.Sprintf("%.1f°C", float64(temperature))
}

func main() {
    var today Temperature = 36.6
    fmt.Println(today)                // fmt calls String() for you
    fmt.Printf("Today: %v\n", today) // %v also uses String()
}
36.6°C
Today: 36.6°C

Any type with String() string satisfies fmt.Stringer. The fmt package checks for it and calls it when printing. That is why you see the °C sign without asking for it.

Program 6: A Custom error Type

error is just an interface with one method: Error() string.

package main

import "fmt"

// StockError says how many of an item are left.
type StockError struct {
    Item string
    Have int
}

// Error makes StockError satisfy the error interface.
func (stockError StockError) Error() string {
    return fmt.Sprintf("only %d %s left", stockError.Have, stockError.Item)
}

// buy returns an error when there is not enough stock.
func buy(item string, quantity, stock int) error {
    if quantity > stock {
        return StockError{item, stock}
    }
    return nil // nil means "no error"
}

func main() {
    fmt.Println(buy("pen", 2, 10))
    fmt.Println(buy("bag", 5, 3))
}
<nil>
only 3 bag left

StockError has an Error() string method, so you can return it as an error. The first call has enough stock and returns nil. We go deeper into custom errors in the next post of this level.

Program 7: io.Writer Sends Output Anywhere

package main

import (
    "fmt"
    "io"
    "os"
    "strings"
)

// report writes one line to any io.Writer.
func report(writer io.Writer, name string, score int) {
    fmt.Fprintf(writer, "%s scored %d\n", name, score) // Fprintf prints to a writer instead of the screen
}

func main() {
    report(os.Stdout, "Ravi", 88) // os.Stdout is the screen

    var builder strings.Builder // a builder collects text in memory
    report(&builder, "Meera", 95)
    fmt.Print("Saved: ", builder.String())
}
Ravi scored 88
Saved: Meera scored 95

report writes to any io.Writer. Here it writes once to the screen and once to a string builder. It could also write to a file or a network connection.

Program 8: Implement sort.Interface

package main

import (
    "fmt"
    "sort"
)

// ByLength is a list of words that sorts by word length.
type ByLength []string

// Len returns how many words there are.
func (words ByLength) Len() int { return len(words) }

// Less says if word i is shorter than word j.
func (words ByLength) Less(i, j int) bool { return len(words[i]) < len(words[j]) }

// Swap swaps two words (a plain swap of two values).
func (words ByLength) Swap(i, j int) { words[i], words[j] = words[j], words[i] }

func main() {
    words := []string{"banana", "fig", "apple", "kiwi"}
    sort.Sort(ByLength(words)) // convert to ByLength so sort can use our methods
    fmt.Println(words)
}
[fig kiwi apple banana]

sort.Sort works with any type that has Len, Less and Swap. It calls those three methods again and again until the list is in order. New code often uses slices.SortFunc instead, as in our Go sorting programs.

Type Checks in Go Interface Programs

Sometimes Go interface programs need the real type stored inside an interface.

Program 9: The Empty Interface any Holds Any Value

Before Go interface programs check types, it helps to see what any can hold.

package main

import "fmt"

func main() {
    var box any // any can hold a value of any type

    box = 10
    fmt.Printf("%v is a %T\n", box, box) // %v prints the value, %T prints the type

    box = "hello"
    fmt.Printf("%v is a %T\n", box, box)

    box = true
    fmt.Printf("%v is a %T\n", box, box)
}
10 is a int
hello is a string
true is a bool

any is an interface with no methods, so every type satisfies it. The same box variable holds an int, then a string, then a bool. %T shows which type is inside at each step.

Program 10: Type Assertion with ok

package main

import "fmt"

// Shape is any type with an Area method.
type Shape interface{ Area() float64 }

// Circle has a radius.
type Circle struct{ Radius float64 }

// Square has one side length.
type Square struct{ Side float64 }

func (circle Circle) Area() float64 { return 3.14 * circle.Radius * circle.Radius }
func (square Square) Area() float64 { return square.Side * square.Side }

func main() {
    var shape Shape = Circle{2}

    // ok is true only if shape really holds a Circle.
    if circle, ok := shape.(Circle); ok {
        fmt.Println("circle with radius", circle.Radius)
    }

    _, ok := shape.(Square) // _ ignores the value, we only want ok
    fmt.Println("is square:", ok)
}
circle with radius 2
is square: false

shape.(Circle) asks “is a Circle inside?”. The two-value form never panics. If you wrote shape.(Square) without ok, the program would panic because shape holds a Circle.

Program 11: Type Switch on any

package main

import "fmt"

// describe returns a short text for each kind of value.
func describe(value any) string {
    switch typed := value.(type) { // typed has the real type in each case
    case int:
        return fmt.Sprintf("int %d", typed)
    case string:
        return fmt.Sprintf("string %q", typed)
    case []int:
        return fmt.Sprintf("slice of %d ints", len(typed))
    case error:
        return "error: " + typed.Error()
    case nil:
        return "nil"
    default:
        return fmt.Sprintf("other %T", typed)
    }
}

func main() {
    values := []any{42, "go", []int{1, 2}, fmt.Errorf("oops"), nil, 3.5}
    for _, value := range values {
        fmt.Println(describe(value))
    }
}
int 42
string "go"
slice of 2 ints
error: oops
nil
other float64

A type switch checks the real type inside value, one case at a time. In each case, typed already has that type, so you can use it directly. A case can name an interface too, like error. See our type assertion and type switch guide for more.

Program 12: Interface Embedding

package main

import "fmt"

// Reader can read text.
type Reader interface{ Read() string }

// Writer can write text.
type Writer interface{ Write(text string) }

// ReadWriter needs both methods.
type ReadWriter interface {
    Reader
    Writer
}

// Notebook stores pages of text.
type Notebook struct{ pages []string }

// Write adds a page (pointer receiver, so it changes the notebook).
func (notebook *Notebook) Write(text string) { notebook.pages = append(notebook.pages, text) }

// Read returns all pages as one string.
func (notebook *Notebook) Read() string { return fmt.Sprint(notebook.pages) }

func main() {
    var readWriter ReadWriter = &Notebook{} // & because the methods use *Notebook
    readWriter.Write("page one")
    readWriter.Write("page two")
    fmt.Println(readWriter.Read())
}
[page one page two]

ReadWriter combines two smaller interfaces. *Notebook has both methods, so it fits. This is exactly how io.ReadWriter is built in the standard library.

Program 13: Compile-Time Interface Check

package main

import "fmt"

// Notifier can send a message.
type Notifier interface{ Notify(message string) string }

// Email sends to one address.
type Email struct{ To string }

// Notify makes Email satisfy Notifier.
func (email Email) Notify(message string) string {
    return "email to " + email.To + ": " + message
}

// Fails to compile if Email stops satisfying Notifier.
var _ Notifier = Email{}

func main() {
    fmt.Println(Email{"asha@example.com"}.Notify("Order shipped"))
}
email to asha@example.com: Order shipped

The line var _ Notifier = Email{} asks the compiler to check the fit. Also, the blank variable costs nothing at run time. It turns a missing method into a clear compile error, right next to the type.

Program 14: A Fake for Testing

package main

import "fmt"

// Store can look up the price of an item.
type Store interface {
    Price(item string) (int, bool)
}

// FakeStore is a simple map that acts like a store in tests.
type FakeStore map[string]int

// Price returns the price and true, or 0 and false if the item is missing.
func (store FakeStore) Price(item string) (int, bool) {
    price, ok := store[item] // ok is true if the item is in the map
    return price, ok
}

// cartTotal adds up the prices of all known items.
func cartTotal(store Store, items []string) int {
    total := 0
    for _, item := range items {
        price, ok := store.Price(item)
        if ok {
            total += price
        }
    }
    return total
}

func main() {
    fake := FakeStore{"pen": 10, "book": 250}
    fmt.Println(cartTotal(fake, []string{"pen", "book", "pen", "lamp"}))
}
270

cartTotal only needs something with a Price method. The fake map gives 10 + 250 + 10 and skips the unknown lamp. In real code, Store would talk to a database, and our Go mocking with interfaces guide shows this in full.

Interface vs Concrete Type in Go Interface Programs

Interfaces are powerful, but Go interface programs should not use them everywhere. The diagram and table below compare them with concrete types.

Go interface programs comparison of interfaces and concrete types
Use an interface when callers need flexibility, and a concrete type when there is only one implementation.
FeatureInterface parameterConcrete type parameter
AcceptsAny type with the methodsOnly that type
Easy to fake in testsYesHarder
SpeedTiny cost per callFastest
Fields visibleNo, only methodsYes
Best forPlug-in behaviour, testsOne fixed implementation

A Go saying sums it up: accept interfaces, return concrete types. Keep interfaces small, often just one or two methods.

Common Mistakes in Go Interface Programs

  • Pointer receiver, value assignment: if Area has a *Circle receiver, a plain Circle does not satisfy Shape.
  • The nil interface trap: an interface holding a nil pointer is not nil, so err != nil can be true.
  • Assertion without ok: s.(Square) panics when the type is wrong. Use the two-value form.
  • Huge interfaces: big interfaces are hard to satisfy and fake. Split them.
  • Interfaces with one implementation: add an interface only when you need a second one, like a test fake.

Best Practices for Go Interface Programs

  • Keep interfaces small, like io.Reader with one method.
  • Define interfaces where they are used, not next to the type that implements them.
  • Use the two-value type assertion whenever the type might differ.
  • Add a compile-time check like var _ Shape = Circle{} for important types.
  • Return concrete types from constructors, so callers keep full access.

Go Interface Programs Interview Questions and Answers

Interviewers use short Go interface programs to test the trickiest rules of interfaces. Each program is complete, with real output from Go 1.27.

Satisfaction Questions in Go Interface Programs

Q1. How does a type implement an interface in Go?

Implicitly. If a type has every method in the interface, with matching names and signatures, it satisfies the interface. There is no implements keyword.

Q2. Why does this program not compile?

package main

// Shape is any type with an Area method.
type Shape interface{ Area() float64 }

// Circle has a radius.
type Circle struct{ Radius float64 }

// Area uses a pointer receiver, so only *Circle has this method.
func (circle *Circle) Area() float64 { return 3.14 * circle.Radius * circle.Radius }

func main() {
    var shape Shape = Circle{2} // a plain Circle value, not a pointer
    _ = shape
}
Circle does not implement Shape (method Area has pointer receiver)

Only *Circle has the Area method, so you must write &Circle{2}. A value type’s method set does not include pointer receiver methods.

Q3. What is the difference between any and interface{}?

There is no difference. any is an alias for interface{}, added in Go 1.18 to make code easier to read.

Nil and Comparison Questions

Q4. What does this program print?

package main

import "fmt"

// MyError is a custom error type.
type MyError struct{}

func (*MyError) Error() string { return "my error" }

// find returns an error interface that holds a *MyError pointer.
func find(fail bool) error {
    var errorPointer *MyError // starts as a nil pointer
    if fail {
        errorPointer = &MyError{}
    }
    return errorPointer // even when nil, the interface remembers the type
}

func main() {
    err := find(false) // err is the error value
    fmt.Println(err == nil)
}
false

This is the famous nil interface trap. The function returns an interface holding a nil *MyError. The interface has a type, so it is not nil. Fix it by returning a plain nil when there is no error.

Q5. What does this program print?

package main

import "fmt"

func main() {
    var empty any       // holds nothing yet
    var first any = 5   // holds the int 5
    var second any = 5  // also holds the int 5
    fmt.Println(empty == nil, first == second, first == 5)
    fmt.Printf("%v %T\n", empty, first)
}
true true true
<nil> int

Interfaces compare equal when they hold the same type and the same value. An empty interface with nothing inside is nil.

Q6. What does this program print?

package main

import "fmt"

func main() {
    var first any = []int{1}
    var second any = []int{1}

    // defer runs this function at the end, and recover catches the panic.
    defer func() {
        fmt.Println("recovered:", recover())
    }()

    fmt.Println(first == second) // slices cannot be compared, so this panics
}
recovered: runtime error: comparing uncomparable type []int

The code compiles, because both are any. But at run time, Go cannot compare slices, so it panics. We used recover to show the message.

Assertion and Output Questions

Q7. If a type assertion fails without ok, what happens?

package main

import "fmt"

func main() {
    var value any = "hello"
    number := value.(int) // value holds a string, not an int
    fmt.Println(number)
}
panic: interface conversion: interface {} is string, not int

The assertion says “I am sure this is an int”, but it is a string. So Go panics and stops the program.

Q8. What does this program print?

package main

import "fmt"

// Animal is anything that makes a sound.
type Animal interface{ Sound() string }
type Dog struct{}
type Cat struct{}

func (Dog) Sound() string { return "Woof" }
func (Cat) Sound() string { return "Meow" }

func main() {
    animals := map[string]Animal{"dog": Dog{}, "cat": Cat{}} // map values are interfaces
    fmt.Println(animals["cat"].Sound(), animals["dog"].Sound())
}
Meow Woof

The map stores both animals as Animal values. Each lookup calls the Sound method of the real type inside.

Q9. What does this program print?

package main

import (
    "fmt"
    "strings"
)

// Upper prints its text in capital letters.
type Upper struct{ text string }

func (upper Upper) String() string { return strings.ToUpper(upper.text) }

func main() {
    shout := Upper{"go is fun"}
    fmt.Println(shout)
    fmt.Printf("%s | %v | %+v\n", shout, shout, shout)
}
GO IS FUN
GO IS FUN | GO IS FUN | GO IS FUN

Once a type has a String method, fmt uses it for %s, %v and %+v.

Q10. Can an interface hold a pointer?

Yes. An interface can hold any type that satisfies it, including pointers. In fact, types with pointer receiver methods are usually stored as pointers in interfaces.

Q11. What does this program print?

package main

import "fmt"

// Speaker can say something.
type Speaker interface{ Speak() string }

// Robot has a name.
type Robot struct{ Name string }

func (robot Robot) Speak() string { return "I am " + robot.Name }

func main() {
    var speaker Speaker = Robot{"R2"}
    robot := speaker.(Robot) // robot is a copy of the Robot inside
    robot.Name = "C3"        // changes only the copy
    fmt.Println(speaker.Speak(), "|", robot.Speak())
}
I am R2 | I am C3

The assertion gives you a copy of the struct. Changing the copy does not change the value inside the interface.

Q12. Why should interfaces be small?

Small interfaces are easy to satisfy, easy to fake in tests and easy to combine. io.Reader has one method, yet hundreds of types in the standard library and beyond satisfy it.

Practice Task

This task is one of the most practical Go interface programs. First, create a Notifier interface with Send(to, msg string) error, and write SMS and Email types that satisfy it. Write a function that sends the same message through a slice of notifiers. Hint: return an error from SMS when the number is shorter than 10 digits.

Official Resources

Quick Recap

  • Go interface programs define behaviour as a set of methods, and types satisfy them implicitly.
  • An interface value holds a type and a value, and it is nil only when both are empty.
  • Use v, ok := x.(T) or a type switch to get the concrete type safely.
  • Pointer receiver methods only belong to the pointer type, so store &T in the interface.
  • Keep interfaces small, define them where they are used, and return concrete types.

What’s Next?

Next, we look at the most used interface in Go. Read Go error handling programs with output, with custom errors, wrapping, errors.Is, errors.As and recover. For interview practice, see the Go interfaces interview questions.