Golang Tutorial 11: Methods and interfaces
Methods on your own types, implicit interfaces, small interfaces like io.Reader, type switches, the nil interface trap and "accept interfaces, return structs", with runnable examples on Go 1.27 and a small io.Writer exercise.
Interfaces are where Go starts to feel different from Java or C#. There is no implements keyword. A type satisfies an interface just by having the right methods, and that one rule changes how you design packages. In this blog we will look at methods on your own types, interfaces, the small interfaces from the standard library like io.Reader, type switches, the nil interface trap and the "accept interfaces, return structs" advice.
Level: beginner. It helps to have read Tutorial 7 on structs and Tutorial 10 on pointers, because pointer receivers matter a lot here. Examples were run on Go 1.27.3.
mkdir ifacedemo && cd ifacedemo
go mod init example.com/ifacedemo
mkdir methods shapes reader typeswitch niliface notifier exercise
Methods on any type you define
A method is a function with a receiver. The receiver can be a struct, but it can also be any named type you define in the same package, like a float64 or a slice.
package main
import (
"fmt"
"strings"
)
type Celsius float64
func (c Celsius) Fahrenheit() float64 { return float64(c)*9/5 + 32 }
type Tags []string
func (t Tags) Has(tag string) bool {
for _, x := range t {
if strings.EqualFold(x, tag) {
return true
}
}
return false
}
func main() {
temp := Celsius(31.5)
fmt.Printf("%.1fC is %.1fF\n", temp, temp.Fahrenheit())
t := Tags{"Golang", "Tutorial"}
fmt.Println(t.Has("golang"), t.Has("docker"))
// A method value: the receiver is bound.
f := temp.Fahrenheit
fmt.Println(f())
// A method expression: the receiver becomes the first argument.
g := Celsius.Fahrenheit
fmt.Println(g(100))
}
31.5C is 88.7F
true false
88.7
212
You can't add methods to type from other packages, so no func (s string) Shout(). Wrap it in your own type instead, like Tags wraps []string.
The method value bit at the end looks like trivia but you'll actually use it. Passing srv.handleLinks as an HTTP handler is a method value.
Interfaces are satisfied implicitly
An interface is a set of method signatures. Any type with those methods satisfies it, without saying so anywhere.
package main
import (
"fmt"
"math"
)
type Shape interface {
Area() float64
Perimeter() float64
}
type Rect struct{ W, H float64 }
type Circle struct{ R float64 }
func (r Rect) Area() float64 { return r.W * r.H }
func (r Rect) Perimeter() float64 { return 2 * (r.W + r.H) }
func (c Circle) Area() float64 { return math.Pi * c.R * c.R }
func (c Circle) Perimeter() float64 { return 2 * math.Pi * c.R }
func (r Rect) String() string { return fmt.Sprintf("rect(%gx%g)", r.W, r.H) }
func (c Circle) String() string { return fmt.Sprintf("circle(r=%g)", c.R) }
// compile-time checks
var (
_ Shape = Rect{}
_ Shape = Circle{}
_ fmt.Stringer = Rect{}
_ fmt.Stringer = Circle{}
)
func totalArea(shapes ...Shape) float64 {
var sum float64
for _, s := range shapes {
sum += s.Area()
}
return sum
}
func main() {
shapes := []Shape{Rect{3, 4}, Circle{1}, Rect{W: 2, H: 2}}
for _, s := range shapes {
fmt.Printf("%-12v area=%6.2f perimeter=%6.2f\n", s, s.Area(), s.Perimeter())
}
fmt.Printf("total area %.2f\n", totalArea(shapes...))
}
rect(3x4) area= 12.00 perimeter= 14.00
circle(r=1) area= 3.14 perimeter= 6.28
rect(2x2) area= 4.00 perimeter= 8.00
total area 19.14
fmt.Stringer is an interface from the standard library with one method, String() string. fmt checks for it when printing, which is how the shapes print nicely.
A small story here. My first version only had String on Circle. The output came out as {3 4 } for the rectangles, because %-12v applied the width to each field of the struct separately. Adding a String method to Rect fixed it. That's implicit interfaces in a nutshell: I didn't register anything, fmt just found the method.
The var _ Shape = Rect{} lines are a common trick. They cost nothing at run time, but if someone renames Area or changes its signature, the build fails right there instead of somewhere far away where a Rect gets used as a Shape.
Method sets and pointer receivers
If Area had a pointer receiver, func (r *Rect) Area(), then *Rect would satisfy Shape but Rect would not. You'd get a compile error like this one:
./main.go:9:15: cannot use Rect{} (value of struct type Rect) as Shape value in variable declaration: Rect does not implement Shape (method Area has pointer receiver)
The fix is to use &Rect{}, or to go back to value receivers. This is basically the main reason I said in the pointers tutorial to pick one receiver style per type.
Small interfaces: io.Reader
The best interfaces in the standard library are tiny. io.Reader has one method:
type Reader interface {
Read(p []byte) (n int, err error)
}
Files, network connections, HTTP bodies, strings.Reader, gzip streams: all of them are readers. So a function that takes an io.Reader works with all of them, and you can write your own reader that wraps another one.
package main
import (
"bufio"
"fmt"
"io"
"os"
"strings"
)
// upperReader wraps any io.Reader and upper-cases ASCII letters.
type upperReader struct {
r io.Reader
}
func (u upperReader) Read(p []byte) (int, error) {
n, err := u.r.Read(p)
for i := range n {
if p[i] >= 'a' && p[i] <= 'z' {
p[i] -= 'a' - 'A'
}
}
return n, err
}
// countLines works with a file, a string, an HTTP body, anything.
func countLines(r io.Reader) (int, error) {
sc := bufio.NewScanner(r)
n := 0
for sc.Scan() {
n++
}
return n, sc.Err()
}
func main() {
src := strings.NewReader("hello from go\nsecond line\n")
if _, err := io.Copy(os.Stdout, upperReader{src}); err != nil {
fmt.Println("copy:", err)
}
n, _ := countLines(strings.NewReader("a\nb\nc\n"))
fmt.Println("lines:", n)
f, err := os.Open("reader/main.go")
if err != nil {
fmt.Println(err)
return
}
defer f.Close()
n, _ = countLines(f)
fmt.Println("lines in main.go:", n)
}
HELLO FROM GO
SECOND LINE
lines: 3
lines in main.go: 53
Run it from the module root, since it opens reader/main.go by a relative path.
countLines doesn't know or care whether it got a file or a string. That makes it trivial to test: pass a strings.Reader and skip the file entirely. One detail in upperReader.Read: it changes only the first n bytes, the ones the inner reader actually filled. The rest of p is garbage from an earlier call.
Type assertions and type switches
An interface value holds two things: a concrete type and a value of that type. A type assertion gets the concrete value back out, and a type switch checks several types in one go.
package main
import (
"errors"
"fmt"
"strconv"
)
func describe(v any) string {
switch x := v.(type) {
case nil:
return "nil"
case int:
return "int " + strconv.Itoa(x*2)
case string:
return fmt.Sprintf("string of %d bytes", len(x))
case []string:
return fmt.Sprintf("%d strings", len(x))
case error:
return "error: " + x.Error()
case fmt.Stringer:
return "stringer: " + x.String()
default:
return fmt.Sprintf("something else (%T)", x)
}
}
type code string
func (c code) String() string { return "code " + string(c) }
func main() {
for _, v := range []any{21, "hello", []string{"a", "b"}, errors.New("boom"), code("x1"), 3.5, nil} {
fmt.Println(describe(v))
}
var v any = "shorty"
s, ok := v.(string)
fmt.Println(s, ok)
n, ok := v.(int)
fmt.Println(n, ok)
}
int 42
string of 5 bytes
2 strings
error: boom
stringer: code x1
something else (float64)
nil
shorty true
0 false
any is just another name for interface{}, the empty interface that every type satisfies. Inside each case, x has that case's type, so x*2 works in the int branch.
Always use the two value form s, ok := v.(string) unless you're sure. The one value form panics when the type is wrong. Order matters in a type switch too, the first matching case wins. A type that is both an error and a Stringer would land in the error branch here.
My honest opinion: if you write a lot of type switches over your own types, the design probably wants a method on the interface instead. Type switches are great at the edges, like decoding JSON or handling errors.
The nil interface trap
This one has a FAQ entry on go.dev itself, and it still catches people.
package main
import "fmt"
type NotFound struct{ Code string }
func (e *NotFound) Error() string { return "not found: " + e.Code }
func findBad(code string) error {
var err *NotFound // nil pointer
if code == "" {
err = &NotFound{Code: code}
}
return err // an interface holding (*NotFound)(nil) is NOT nil
}
func findGood(code string) error {
if code == "" {
return &NotFound{Code: code}
}
return nil
}
func main() {
err := findBad("abc")
fmt.Println("bad: err == nil?", err == nil)
fmt.Printf("bad: %T %v\n", err, err == (*NotFound)(nil))
err = findGood("abc")
fmt.Println("good: err == nil?", err == nil)
}
bad: err == nil? false
bad: *main.NotFound true
good: err == nil? true
An interface is only nil when both its type and value are nil. findBad returns an interface whose type is *NotFound and whose value is a nil pointer. So err != nil is true and the caller thinks something failed. The fix is boring: return a literal nil for the success path, never a typed nil pointer.
Accept interfaces, return structs
This is the design advice you'll hear most. Functions take the smallest interface they need, and constructors return the concrete type. The interface is usually declared by the code that uses it.
package main
import (
"fmt"
"strings"
)
// The consumer defines the small interface it needs.
type Notifier interface {
Notify(to, msg string) error
}
// EmailClient is a concrete type with more methods than any one caller needs.
type EmailClient struct {
From string
sent int
}
// NewEmailClient returns the struct, not an interface.
func NewEmailClient(from string) *EmailClient { return &EmailClient{From: from} }
func (e *EmailClient) Notify(to, msg string) error {
e.sent++
fmt.Printf("email %s -> %s: %s\n", e.From, to, msg)
return nil
}
func (e *EmailClient) Sent() int { return e.sent }
// SignupService accepts the interface.
type SignupService struct {
n Notifier
}
func (s SignupService) Register(email string) error {
if !strings.Contains(email, "@") {
return fmt.Errorf("bad email %q", email)
}
return s.n.Notify(email, "welcome to shorty")
}
// fakeNotifier is all a test needs.
type fakeNotifier struct{ got []string }
func (f *fakeNotifier) Notify(to, msg string) error {
f.got = append(f.got, to)
return nil
}
func main() {
email := NewEmailClient("noreply@example.com")
svc := SignupService{n: email}
_ = svc.Register("asha@example.com")
fmt.Println("sent:", email.Sent())
fake := &fakeNotifier{}
svc = SignupService{n: fake}
_ = svc.Register("ravi@example.com")
fmt.Println(svc.Register("not-an-email"))
fmt.Println("fake got:", fake.got)
}
email noreply@example.com -> asha@example.com: welcome to shorty
sent: 1
bad email "not-an-email"
fake got: [ravi@example.com]
Because NewEmailClient returns *EmailClient, main can still call Sent(), which isn't part of Notifier. If the constructor returned Notifier, that method would be hidden and you'd need a type assertion to get it back. And SignupService can be tested with a fake that is six lines long.
I used the same pattern in my golang trading jobs, written up in switching between Gemini and Ollama behind one Go interface. One tiny interface with a single Generate method lets an environment variable pick the model behind it.
A Go 1.27 note: generic methods
Go 1.27 added generic methods, so a method can now have its own type parameters. I tried it straight away, and the release notes are right that they can't satisfy an interface:
package main
type Box struct{ items []any }
func (b *Box) Put[T any](v T) { b.items = append(b.items, v) }
type Putter interface {
Put(v int)
}
var _ Putter = &Box{}
func main() {}
./main.go:11:16: cannot use &Box{} (value of type *Box) as Putter value in variable declaration: *Box does not implement Putter (wrong type for method Put)
have Put[T any](T)
want Put(int)
The method itself work fine when you call it directly. Just don't expect it to fill an interface slot. Generics get their own tutorial later in this series.
Exercise
Write a countingWriter that wraps any io.Writer, passes every write through, and counts the bytes. Then use it with fmt.Fprintf and io.WriteString on a strings.Builder and print the count. Think about whether Write needs a pointer receiver. It does, and this is a sneaky one. Now what happens is, with a value receiver everything still compiles, but the count stays at 0 because each Write bumps a copy.
package main
import (
"fmt"
"io"
"strings"
)
// countingWriter wraps an io.Writer and counts bytes written.
type countingWriter struct {
w io.Writer
n int64
}
func (c *countingWriter) Write(p []byte) (int, error) {
n, err := c.w.Write(p)
c.n += int64(n)
return n, err
}
func main() {
var sb strings.Builder
cw := &countingWriter{w: &sb}
fmt.Fprintf(cw, "hello %s\n", "gopher")
io.WriteString(cw, "two\n")
fmt.Print(sb.String())
fmt.Println("bytes:", cw.n)
}
hello gopher
two
bytes: 17
Note &sb and not sb. strings.Builder has a pointer receiver on Write, so only *strings.Builder is an io.Writer. Same rule as the method sets section, showing up in the standard library.