Explain it simply
Explain it simply
Think of an interface as a job description. If it says "must be able to Notify(message string)", then an email sender, an SMS sender or a Telegram bot can all take the job, as long as they can do that. The calling function does not know who it got; it only says "please Notify".
The twist in Go is that nobody has to apply for the job. You never write implements Notifier as in Java; once a type has the required methods with exactly matching names, parameters and return types, the compiler accepts it automatically.
Problem → Why → Solution
The problem: a function welded to one concrete type
sendAlert() was written to take an EmailNotifier, so when the team wants SMS alerts too, someone copy-pastes it into sendAlertSMS(). A Telegram channel would mean a third copy. Tests have no way to check the alert logic without sending a real email.
func sendAlert(e EmailNotifier) { // only email can be passed
e.Notify("Server is running")
}
func sendAlertSMS(s SMSNotifier) { // a copy of the same logic
s.Notify("Server is running")
}
// sendAlert(SMSNotifier{}) -> compile error: cannot use SMSNotifier{}
// (value of struct type SMSNotifier) as EmailNotifier value in argument to sendAlertWhy does this happen?
sendAlert() does not need anything specific to email; it only needs to call Notify(). Declaring the parameter as a concrete struct makes the function demand far more than it uses. Change the parameter to a Notifier interface and any type with a Notify method is accepted, so one function is enough.
Core concept: an interface is a method set
type Notifier interface { Notify(message string) } gives a name to a list of method signatures. Any type that has all of those methods satisfies Notifier; this is called implicit satisfaction. It means you can declare an interface later, even for types from packages you do not own, without touching those packages. The signatures must match exactly: a Notify(msg string) error with a different return type does not satisfy it.
At runtime an interface value holds two parts: a dynamic type (for example EmailNotifier) and a dynamic value (the actual value of that type). Calling n.Notify() looks up Notify on the dynamic type and calls it. The zero value of an interface is nil, meaning there is neither a type nor a value, and calling a method on a nil interface panics.
The method-set rule from the Methods lesson matters here. If Notify is written as func (s *SMS) Notify(...) with a pointer receiver, only *SMS is a Notifier, and putting an SMS value into a Notifier variable is a compile error mentioning "method Notify has pointer receiver". You store &SMS{...} instead.
Go culture favors small interfaces. The standard library's io.Writer has a single Write method and fmt.Stringer has a single String(). Declare an interface on the consumer side and include only the methods that code really calls. A common saying is "accept interfaces, return structs": take parameters as interfaces, but have constructors return concrete types. any, an alias for interface{}, has no methods, so every type satisfies it, but it throws away type safety, so use it only when you truly must.
- Store a concrete value in it
- It records the (type, value) pair
- A call runs that type's method
- nil only if type and value are empty
An interface whose type is set but whose value is a nil pointer is still not nil.
General pattern
type InterfaceName interface {
MethodName(param ParamType) ResultType
}
func (t ConcreteType) MethodName(param ParamType) ResultType { ... }
func consumer(x InterfaceName) { x.MethodName(arg) }
var _ InterfaceName = ConcreteType{} // optional compile-time checkAn interface lists method signatures with no bodies. A concrete type satisfies it by having methods with those exact signatures. The var _ InterfaceName = ... line does nothing at runtime; it only makes the compiler complain early if the type stops matching.
Example: sending an alert through a Notifier
In this example sendAlert() accepts the Notifier interface, and EmailNotifier can be passed in just because it has a Notify method, with no implements clause. Notice also that EmailNotifier has no fields, so its receiver is written as just (EmailNotifier) without a name.
package main
import "fmt"
type Notifier interface {
Notify(message string)
}
type EmailNotifier struct{}
func (EmailNotifier) Notify(message string) {
fmt.Println("Email:", message)
}
func sendAlert(n Notifier) {
n.Notify("Server is running")
}
func main() {
email := EmailNotifier{}
sendAlert(email)
}Code breakdown
- Interface
type Notifier interface {Declares the Notifier behavior contract. It can be used anywhere a type can: parameters, variables, slice elements.
- Method signature
Notify(message string)A signature with no body. A satisfying type needs exactly this name, this parameter type and no return value.
- Concrete method
func (EmailNotifier) Notify(message string) {Because it uses a value receiver, both EmailNotifier and *EmailNotifier are Notifiers. The word "implements" appears nowhere.
- Consumer
func sendAlert(n Notifier) {sendAlert does not know which type is inside n, only that it can call Notify. Adding an SMS type later requires no change here.
- Call
sendAlert(email)email is converted to a Notifier holding the pair (EmailNotifier, {}), and the program prints "Email: Server is running".
Email: Server is runningPointer receivers and a compile-time check
SMS stores a phone number and implements Notify with a pointer receiver, so you put &SMS{...} into a Notifier variable. The line var _ Notifier = (*SMS)(nil) costs nothing at runtime; it asks the compiler to confirm that *SMS satisfies Notifier, so if someone later changes the Notify signature, this line fails immediately.
package main
import "fmt"
type Notifier interface {
Notify(message string)
}
type SMS struct{ Phone string }
func (s *SMS) Notify(message string) {
fmt.Println("SMS to", s.Phone+":", message)
}
// Compile-time check: *SMS must satisfy Notifier.
var _ Notifier = (*SMS)(nil)
func main() {
var n Notifier = &SMS{Phone: "09-111"}
n.Notify("disk 90% full")
fmt.Printf("dynamic type: %T\n", n)
// var bad Notifier = SMS{Phone: "09-222"}
// compile error: SMS does not implement Notifier
// (method Notify has pointer receiver)
}Type assertions and type switches
To get the concrete type back out of an interface, use a type assertion such as v.(string). The comma-ok form, s, ok := v.(string), sets ok to false on a mismatch instead of panicking; without ok, a mismatch panics. When several types are possible, switch x := v.(type) lets each case use x as that case's type. A case can also name an interface such as fmt.Stringer, and cases are checked from top to bottom.
package main
import "fmt"
type Kyat int
func (k Kyat) String() string { return fmt.Sprintf("%d MMK", int(k)) }
func describe(v any) string {
switch x := v.(type) {
case nil:
return "nothing"
case int:
return fmt.Sprintf("int %d, doubled %d", x, x*2)
case string:
return fmt.Sprintf("string of %d bytes", len(x))
case fmt.Stringer:
return "Stringer: " + x.String()
default:
return fmt.Sprintf("other type %T", x)
}
}
func main() {
for _, v := range []any{21, "Mingalaba", Kyat(5000), 3.5, nil} {
fmt.Println(describe(v))
}
var v any = "hello"
_, isInt := v.(int) // comma-ok: no panic on mismatch
fmt.Println("is int?", isInt)
}The output is "int 21, doubled 42", "string of 9 bytes", "Stringer: 5000 MMK", "other type float64", "nothing" and "is int? false". Kyat's underlying type is int, yet it does not match case int: a type switch compares the exact named type.
An interface holding a nil pointer is not nil
This is the interface trap people hit most often in Go. When validate() returns a nil pointer of type *ValidationError as an error, the interface receives the pair (type=*ValidationError, value=nil). The type half is not empty, so err == nil is false and the caller believes something failed when nothing did. The fix is simple: when there is no error, return the literal nil, not a typed variable.
package main
import "fmt"
type ValidationError struct{ Field string }
func (e *ValidationError) Error() string { return "invalid " + e.Field }
func validate(name string) error {
var verr *ValidationError // nil pointer
if name == "" {
verr = &ValidationError{Field: "name"}
}
return verr // BUG: a nil *ValidationError inside a non-nil error
}
func validateFixed(name string) error {
if name == "" {
return &ValidationError{Field: "name"}
}
return nil // a truly nil interface
}
func main() {
err := validate("Aye")
fmt.Println("buggy err == nil:", err == nil)
fmt.Printf("buggy dynamic type: %T\n", err)
err = validateFixed("Aye")
fmt.Println("fixed err == nil:", err == nil)
}What err holds
--------------
return verr (verr is a nil *ValidationError)
err = [ type: *ValidationError | value: nil ] -> err != nil
return nil
err = [ type: (none) | value: nil ] -> err == nilIn real projects
Where this shows up in real projects
Nearly every Go program uses interfaces all day. fmt.Fprintf() accepts an io.Writer, so the same function can write to a file, a network connection, an HTTP response or a bytes.Buffer. In net/http, http.Handler is an interface with a single ServeHTTP method, and error itself is an interface with a single Error() string method.
In application code their biggest payoff is testing. If OrderService keeps a PaymentGateway interface as a field, production wires in the real payment client while tests plug in a fake gateway that moves no money. Because the interface is declared on the service side with only a method or two, such as Charge(amount int) error, the fake is tiny to write. Plugin systems and swappable storage backends (memory, file, database) are built the same way.
Common mistakes
Common mistakes
1. A signature that is almost right
If the interface asks for Notify(message string) but the type has Notify(message string) error or Notify(msg []byte), it does not satisfy the interface; the compiler reports "does not implement Notifier (wrong type for method Notify)". The method name, parameter types and return types must all match exactly.
2. Storing a value when the methods have pointer receivers
When Notify has an (s *SMS) receiver, var n Notifier = SMS{} fails with "method Notify has pointer receiver". Store &SMS{} instead. Switching to a value receiver is often the wrong fix, because a method that changes fields still needs the pointer.
3. Returning a typed nil pointer as an error
Writing var err *MyError; return err makes err != nil true at the caller. On the no-error path always write return nil directly, and declare the function's return type as error, not *MyError.
4. Designing big interfaces up front
Writing a ten-method interface for a type that has only one implementation makes fakes painful and changes expensive. Wait until a real consumer needs it, then declare an interface with just the methods that consumer calls.
Mini challenge
Mini challenge: areas of mixed shapes
Write a Shape interface with Area() and Perimeter(), put Circles and Squares into one slice, and compute the total area. Use a type switch to give each shape a label.
- Circle{R} and Square{Side} both satisfy Shape implicitly
- totalArea(shapes []Shape) float64 sums areas without knowing the concrete types
- label(s Shape) string uses a type switch to return "circle r=1.0" or "square side=2.0"
- Numbers are printed with %.2f (two decimals)
package main
import (
"fmt"
"math"
)
type Shape interface {
// TODO: Area() and Perimeter(), both returning float64
}
// TODO: Circle and Square structs, plus their two methods each (use math.Pi)
func totalArea(shapes []Shape) float64 {
// TODO: add up s.Area() for every shape
return 0
}
func label(s Shape) string {
// TODO: switch v := s.(type) { ... }
return ""
}
func main() {
// TODO: shapes := []Shape{Circle{R: 1}, Square{Side: 2}, Circle{R: 0.5}}
// TODO: print label, area and perimeter of each shape, then the total
fmt.Println("todo")
}
var _ = math.Pi // delete this line once Circle uses math.PiExpected: The program prints: circle r=1.0 area=3.14 perimeter=6.28 square side=2.0 area=4.00 perimeter=8.00 circle r=0.5 area=0.79 perimeter=3.14 total area: 7.93
Show hint
With value receivers you can put Circle{R: 1} into a []Shape without &. To line the labels up in a column, give them a width with fmt.Printf("%-16s ...").
Show solution
package main
import (
"fmt"
"math"
)
type Shape interface {
Area() float64
Perimeter() float64
}
type Circle struct{ R float64 }
type Square struct{ Side float64 }
func (c Circle) Area() float64 { return math.Pi * c.R * c.R }
func (c Circle) Perimeter() float64 { return 2 * math.Pi * c.R }
func (s Square) Area() float64 { return s.Side * s.Side }
func (s Square) Perimeter() float64 { return 4 * s.Side }
func totalArea(shapes []Shape) float64 {
sum := 0.0
for _, s := range shapes {
sum += s.Area()
}
return sum
}
func label(s Shape) string {
switch v := s.(type) {
case Circle:
return fmt.Sprintf("circle r=%.1f", v.R)
case Square:
return fmt.Sprintf("square side=%.1f", v.Side)
default:
return "unknown shape"
}
}
func main() {
shapes := []Shape{Circle{R: 1}, Square{Side: 2}, Circle{R: 0.5}}
for _, s := range shapes {
fmt.Printf("%-16s area=%.2f perimeter=%.2f\n", label(s), s.Area(), s.Perimeter())
}
fmt.Printf("total area: %.2f\n", totalArea(shapes))
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- An interface is a list of method signatures; any type with exactly those methods satisfies it implicitly.
- When the methods have pointer receivers, only *T satisfies the interface.
- An interface value is a (type, value) pair and is not nil while it holds a nil pointer, so return a literal nil on success.
- Comma-ok type assertions and type switches safely recover the concrete type inside an interface.
- Keep interfaces small and declare them where they are consumed.
A Tour of Go — Go