Interfaces
Course contents (17 lessons)
- Getting started with Go
- Installing Go 1.25 and your first program
- Variables, types and constants
- Control flow: if, for and switch
- Functions, multiple returns and defer
- Slices and maps
- Arrays and slices
- Maps and working with strings
- Structs, methods and interfaces
- Structs, methods and pointers
- Interfaces
- Errors, packages and generics
- Error handling the Go way
- Packages and modules
- Generics
- Concurrency
- Goroutines and channels
- select, timeouts and context
- Mutexes, sync and the race detector
- Testing
- Testing and benchmarks
- Building and shipping a service
- Building an HTTP JSON API with net/http
- Building and deploying a Go service
Behaviour, not hierarchy
An interface describes what something can do, as a list of method signatures. Any type that has those methods satisfies the interface automatically. There is no implements keyword. This is called implicit satisfaction, and it is one of the best design decisions in Go.
package main
import (
"fmt"
"strings"
)
type Notifier interface {
Notify(to, message string) error
}
type EmailNotifier struct{ From string }
func (e EmailNotifier) Notify(to, message string) error {
if !strings.Contains(to, "@") {
return fmt.Errorf("invalid email address %q", to)
}
fmt.Printf("[email from %s] to %s: %s\n", e.From, to, message)
return nil
}
type SMSNotifier struct{}
func (SMSNotifier) Notify(to, message string) error {
fmt.Printf("[sms] to %s: %s\n", to, message)
return nil
}
// OrderService depends on the behaviour, not on a concrete type.
type OrderService struct {
notifier Notifier
}
func (s OrderService) Place(customer, contact string, total int) error {
msg := fmt.Sprintf("Order placed for %s, total Rs %d", customer, total)
return s.notifier.Notify(contact, msg)
}
func describe(v any) string {
switch x := v.(type) {
case int:
return fmt.Sprintf("int %d", x)
case string:
return "string " + x
case Notifier:
return "something that can notify"
case nil:
return "nil"
default:
return fmt.Sprintf("other %T", x)
}
}
func main() {
services := []OrderService{
{notifier: EmailNotifier{From: "shop@example.com"}},
{notifier: SMSNotifier{}},
}
for _, s := range services {
if err := s.Place("Ali", "ali@example.com", 5002); err != nil {
fmt.Println("error:", err)
}
}
bad := OrderService{notifier: EmailNotifier{From: "shop@example.com"}}
fmt.Println(bad.Place("Sara", "not-an-email", 100))
fmt.Println(describe(42))
fmt.Println(describe("hi"))
fmt.Println(describe(SMSNotifier{}))
fmt.Println(describe(3.14))
}
Output:
[email from shop@example.com] to ali@example.com: Order placed for Ali, total Rs 5002
[sms] to ali@example.com: Order placed for Ali, total Rs 5002
invalid email address "not-an-email"
int 42
string hi
something that can notify
other float64
What happened here
Neither EmailNotifier nor SMSNotifier mentions Notifier. They just have a method with the right signature, and that is enough. OrderService accepts the interface, so it works with either, and with any type someone writes in future, including a fake one in a test. That is the main reason interfaces matter in practice: they let you swap implementations and test code without real email servers.
Keep interfaces small
The Go proverb is "the bigger the interface, the weaker the abstraction". The best known interfaces in the standard library have one method: io.Reader has Read, io.Writer has Write, fmt.Stringer has String, and error has Error. Small interfaces are easy to implement and easy to fake. If your interface has eight methods, split it.
Another Go habit: define the interface where it is used, not where the type is defined. The consumer says "I need something with a Notify method". The package that implements notifications does not need to know about it. This is the opposite of what Java programmers expect, and it removes a lot of coupling.
The empty interface and any
An interface with no methods is satisfied by every type. It is written any (an alias for interface{}). A value of type any can hold anything, but you lose type safety: you must find out what is inside before using it. Use any only at real boundaries, such as decoding unknown JSON. With generics, which we meet soon, you rarely need it elsewhere.
Type assertions and type switches
To get the concrete value back from an interface, use a type assertion: s, ok := v.(string). With the comma-ok form it gives ok == false if the type does not match. Without ok, it panics on a mismatch, so use the safe form. A type switch, as in describe, checks several types in turn. Notice that a case can also be an interface type, like Notifier.
The nil interface gotcha
An interface value has two parts: a type and a value. It is only equal to nil if both are empty. This catches many experienced programmers:
type MyErr struct{}
func (*MyErr) Error() string { return "boom" }
func find() error {
var e *MyErr = nil
return e // returns a non-nil interface holding a nil pointer
}
func main() {
if err := find(); err != nil {
fmt.Println("unexpected: err is not nil")
}
}
The function returns a typed nil pointer inside an error interface. The interface has a type, so it does not equal nil, and the check passes when you expected it not to. The fix: return a literal nil when there is no error, and never return a typed nil pointer as an interface.
Compile-time checks
Because satisfaction is implicit, a typo in a method name only shows up where you use the type. If you want the compiler to check early that a type implements an interface, add this line near the type:
var _ Notifier = EmailNotifier{}
Common mistakes
- Making an interface first. Do not create interfaces "just in case". Write concrete code, and extract an interface when you need a second implementation or a test double.
- Pointer versus value method sets. If a method has a pointer receiver, only the pointer type (
*T) satisfies the interface, notT. The error isT does not implement X (method M has pointer receiver). - Returning interfaces from constructors. The guideline is "accept interfaces, return structs". Return the concrete type, and let callers decide what interface they want.
Try it yourself
Define an interface Shape with Area() float64 and Perimeter() float64. Implement it for Rectangle and Circle. Write a function that takes a []Shape and prints the total area. Then add a String() method to both types so fmt.Println prints them nicely, and add the var _ Shape = ... check lines.
package main
import (
"fmt"
"strings"
)
type Notifier interface {
Notify(to, message string) error
}
type EmailNotifier struct{ From string }
func (e EmailNotifier) Notify(to, message string) error {
if !strings.Contains(to, "@") {
return fmt.Errorf("invalid email address %q", to)
}
fmt.Printf("[email from %s] to %s: %s\n", e.From, to, message)
return nil
}
type SMSNotifier struct{}
func (SMSNotifier) Notify(to, message string) error {
fmt.Printf("[sms] to %s: %s\n", to, message)
return nil
}
// OrderService depends on the behaviour, not on a concrete type.
type OrderService struct {
notifier Notifier
}
func (s OrderService) Place(customer, contact string, total int) error {
msg := fmt.Sprintf("Order placed for %s, total Rs %d", customer, total)
return s.notifier.Notify(contact, msg)
}
func describe(v any) string {
switch x := v.(type) {
case int:
return fmt.Sprintf("int %d", x)
case string:
return "string " + x
case Notifier:
return "something that can notify"
case nil:
return "nil"
default:
return fmt.Sprintf("other %T", x)
}
}
func main() {
services := []OrderService{
{notifier: EmailNotifier{From: "shop@example.com"}},
{notifier: SMSNotifier{}},
}
for _, s := range services {
if err := s.Place("Ali", "ali@example.com", 5002); err != nil {
fmt.Println("error:", err)
}
}
bad := OrderService{notifier: EmailNotifier{From: "shop@example.com"}}
fmt.Println(bad.Place("Sara", "not-an-email", 100))
fmt.Println(describe(42))
fmt.Println(describe("hi"))
fmt.Println(describe(SMSNotifier{}))
fmt.Println(describe(3.14))
}
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account