Implicit satisfaction and type switches
Go interfaces are satisfied implicitly: a type has a method set, and an interface asks for some methods, and the assignment succeeds when the set contains the request. Nothing in the type declaration mentions the interface, which is why an interface can be written after the types that satisfy it, in another package. The previous lesson used that to dispatch; this one checks and branches on it.
Satisfaction checked at compile time
A package that relies on a type satisfying an interface should say so in one line: var _ Shape = (*Circle)(nil) compiles only when *Circle has the method. The blank identifier throws the value away and the check costs nothing at run time; its purpose is to turn a removed method into a build error at the definition site instead of a failed assignment in a distant package. Both forms are written when value and pointer receivers differ.
package main
import "fmt"
type Shape interface {
Area() float64
}
type Circle struct{ R float64 }
func (c Circle) Area() float64 { return 3.14 * c.R * c.R }
var _ Shape = Circle{}
var _ Shape = (*Circle)(nil)
func main() {
shapes := []Shape{Circle{1}, Circle{2}}
for _, s := range shapes {
fmt.Printf("%.2f\n", s.Area())
}
}
go run assert.go
3.14
12.56
The two assertions cover the two receiver kinds: Circle{} and (*Circle)(nil) are different method sets. A test that asserts the pointer form and a library that passes a value will still fail, so the assertion must name the form the code uses.
A type switch
A type switch is the multi-way form of a type assertion. Each case names one type or a list of types, the variable has that type inside the case, and nil is a case of its own because an interface can hold nothing. The order matters: the first case that matches wins, so a concrete type must come before the interface it satisfies.
package main
import "fmt"
type Celsius float64
func (c Celsius) String() string { return fmt.Sprintf("%.0f°C", float64(c)) }
func describe(v any) string {
switch x := v.(type) {
case nil:
return "nothing"
case int:
return fmt.Sprintf("int %d", x)
case string:
return "string " + x
case fmt.Stringer:
return "stringer " + x.String()
default:
return fmt.Sprintf("other %T", x)
}
}
func main() {
for _, v := range []any{42, "go", Celsius(20), nil, 3.5} {
fmt.Println(describe(v))
}
}
go run switch.go
int 42
string go
stringer 20°C
nothing
other float64
The Celsius value matched fmt.Stringer after the int and string cases had failed, and the float fell through to the default. Putting case fmt.Stringer first would have caught Celsius and hidden any later case, which is the one ordering mistake this construct invites.
Interfaces built from interfaces
An interface can embed another interface and inherit its methods, so a small set of one-method interfaces composes into the larger contracts: io.Reader, io.Writer and io.ReadWriter are exactly this. A type that already has both methods satisfies the combined interface without any declaration.
package main
import (
"bytes"
"fmt"
)
type Reader interface {
Read(p []byte) (int, error)
}
type Writer interface {
Write(p []byte) (int, error)
}
type ReadWriter interface {
Reader
Writer
}
func main() {
var rw ReadWriter = &bytes.Buffer{}
fmt.Fprint(rw, "hello")
buf := make([]byte, 3)
n, _ := rw.Read(buf)
fmt.Printf("read %d bytes: %q\n", n, buf[:n])
}
go run embed.go
read 3 bytes: "hel"
bytes.Buffer has Read and Write, so it satisfied ReadWriter on the spot, which is why the program needed no new type. The rule for a good interface is one or two methods, named after what the caller wants to do, so that many types satisfy it by accident and composition stays cheap.
An optional interface
A function that takes any can ask whether the value also has a richer method, which is how the standard library detects io.Closer or encoding.TextMarshaler without requiring them. The comma-ok assertion makes the extra capability optional: a value without it takes the general path.
package main
import "fmt"
type Sized interface {
Len() int
}
type buffer struct {
data string
}
func (b buffer) Len() int { return len(b.data) }
func main() {
values := []any{buffer{"abc"}, "abc", []int{1, 2}}
for _, v := range values {
if s, ok := v.(Sized); ok {
fmt.Printf("%T has Len %d\n", v, s.Len())
} else {
fmt.Printf("%T has no Len\n", v)
}
}
}
go run optional.go
main.buffer has Len 3
string has no Len
[]int has no Len
The buffer and the plain string both have a length, but only the buffer has a Len method, so only it took the special path. A string is a built-in type and cannot gain methods, which is why the standard library defines interfaces for the conversions it needs rather than extending the built-in types.
A type switch needs an interface
The switch inspects the dynamic type of an interface value, and a plain int has no dynamic type to inspect. The compiler rejects the construct rather than wrapping the value in an interface, because the wrapper would allocate and the answer would always be the same case.
package main
import "fmt"
func main() {
var x int = 1
switch x.(type) {
case int:
fmt.Println("int")
}
}
go build -o badswitch badswitch.go
# command-line-arguments
./badswitch.go:7:9: x (variable of type int) is not an interface
The message is short because the mistake is a type error, not a missing method. Assign the value to an any first when a switch on a concrete type is genuinely wanted, and the compiler will build the wrapper at the assignment.
Exercises
- Add var _ fmt.Stringer = (*Temperature)(nil) to a type with a pointer receiver and then change the receiver to a value. What does the compiler say, and why does the pointer form still compile?
- Extend describe with a case for []int and one for error. Which case must come first if an error type also has a String method?
- Write a ReadWriter implementation backed by a strings.Builder for writes and a byte slice for reads, and assert at compile time that it satisfies the interface.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
How does a Go type come to satisfy an interface?
Answer
By having the methods the interface lists, with no declaration
Satisfaction is structural and implicit: the method set is the whole story.
-
What does this program print?
package main import "fmt" type Shape interface { Area() float64 } type Circle struct{ R float64 } func (c Circle) Area() float64 { return 3.14 * c.R * c.R } var _ Shape = Circle{} var _ Shape = (*Circle)(nil) func main() { shapes := []Shape{Circle{1}, Circle{2}} for _, s := range shapes { fmt.Printf("%.2f\n", s.Area()) } }Answer
3.14 / 12.56
The areas are 3.14 times one squared and 3.14 times two squared.
-
What does var _ Shape = (*Circle)(nil) do?
Answer
Checks at compile time that *Circle satisfies Shape
It is a compile-time assertion; the value itself is never used.
-
What does the third line of this program print, for Celsius(20)?
package main import "fmt" type Celsius float64 func (c Celsius) String() string { return fmt.Sprintf("%.0f°C", float64(c)) } func describe(v any) string { switch x := v.(type) { case nil: return "nothing" case int: return fmt.Sprintf("int %d", x) case string: return "string " + x case fmt.Stringer: return "stringer " + x.String() default: return fmt.Sprintf("other %T", x) } } func main() { for _, v := range []any{42, "go", Celsius(20), nil, 3.5} { fmt.Println(describe(v)) } }Answer
int 42 / string go / stringer 20°C / nothing / other float64
Celsius has a String method, so it matches the fmt.Stringer case before the default.
-
What happens when several type switch cases could match?
Answer
The first matching case wins
A type switch is evaluated in order, so the concrete cases must come before the interface cases.
-
What does this program print?
package main import ( "bytes" "fmt" ) type Reader interface { Read(p []byte) (int, error) } type Writer interface { Write(p []byte) (int, error) } type ReadWriter interface { Reader Writer } func main() { var rw ReadWriter = &bytes.Buffer{} fmt.Fprint(rw, "hello") buf := make([]byte, 3) n, _ := rw.Read(buf) fmt.Printf("read %d bytes: %q\n", n, buf[:n]) }Answer
read 3 bytes: "hel"
The buffer held hello and the read took the first three bytes.
-
Why is io.ReadWriter written as two embedded interfaces?
Answer
So small interfaces compose and a type with both methods satisfies it implicitly
Composition of one-method interfaces is the standard library's design rule.
-
What does this program print?
package main import "fmt" type Sized interface { Len() int } type buffer struct { data string } func (b buffer) Len() int { return len(b.data) } func main() { values := []any{buffer{"abc"}, "abc", []int{1, 2}} for _, v := range values { if s, ok := v.(Sized); ok { fmt.Printf("%T has Len %d\n", v, s.Len()) } else { fmt.Printf("%T has no Len\n", v) } } }Answer
main.buffer has Len 3 / string has no Len / []int has no Len
Only the buffer has a Len method; a string and a slice of ints have none.
-
What does the compiler say about this program?
package main import "fmt" func main() { var x int = 1 switch x.(type) { case int: fmt.Println("int") } }Answer
x (variable of type int) is not an interface
A type switch needs an interface value to inspect; assign to any first.
-
When should the compile-time assertion be written?
Answer
In the package that defines the type or the interface, when the code relies on the match
It moves a missing method from a distant assignment to the definition, where it is easy to fix.
The code on this page was run with go 1.26.10 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev