1. type assertion in typed Go
When you are learning Go, it feels like “the type system solves everything”, and in many places it really does. But interfaces are intentionally designed so that a variable can hold a value of different concrete types, united by common behavior. This is useful, but sometimes it creates the feeling: “Okay, I know there is something inside, but what exactly is it?”
The most real-life example is a variable of type error. It tells us only one thing: “I have a method Error() string.” But which exact error type it is and what additional fields/methods it has is hidden behind the interface.
The standard library directly pushes you toward the idea that sometimes you need to determine: “is this error temporary?” or “is this a timeout?” — and then you check whether the error implements a richer interface, for example net.Error, which has methods Timeout() and Temporary(). This is exactly the case where type assertion is used.
Type assertion is your “flashlight” in the dark room of interfaces: it does not break doors and does not cause panic (if used safely), but it lets you see the specifics when needed.
2. Syntax and forms of type assertion
Type assertion looks like this:
v, ok := x.(T)
It reads roughly like this: “try to extract value of type T from x; if it works — put it into v and set ok = true, otherwise set ok = false.”
Important: x must have an interface type. Most often this is:
- any (the same as interface{})
- error
- your interface (for example, io.Reader, fmt.Stringer, MyInterface)
And T can be:
- a concrete type (int, string, Task, *Task)
- an interface (fmt.Stringer, error, your interface)
At this point beginners often have a “micro brain explosion”: “How is it that you check an interface, if x is already an interface?” That is fine: you are checking not “interface-ness”, but the presence of specific behavior / a set of methods in the value inside x.
Safe form and ok: why you cannot ignore it
Let us first look at a short example “in vacuum”, so as not to mix several topics in your head at once.
package main
import "fmt"
func main() {
var x any = "10"
n, ok := x.(int)
fmt.Println(n, ok) // 0 false
}
Why is the output 0 false? Because when the assertion fails, n gets the zero value for type int, that is 0.
And here is the trickiness: zero value sometimes looks “almost normal”, and you may not notice that the “wrong type” branch happened.
A rule that really saves hours of life: if you use v, ok := ..., then ok must definitely be checked.
A very typical Go pattern is “check and early return”:
package main
import "fmt"
func printAsInt(x any) {
n, ok := x.(int)
if !ok {
fmt.Printf("not an int: type=%T\n", x) // not an int: type=string
return
}
fmt.Println("int:", n) // int: 42
}
func main() {
printAsInt("42")
printAsInt(42)
}
Notice: we are not trying to “work around it somehow”; we honestly record “wrong type” and return. In Go this is a normal, healthy programming style: quickly filter out bad cases, then live more simply.
Unsafe form v := x.(T) and when it is allowed
There is a form without ok:
v := x.(T)
It looks simpler — and that is exactly why it is more dangerous: if x contains something other than T, the program will get a panic.
A panic is not a “compile error”, but a runtime crash. Sometimes it is acceptable (for example, in tests or under a very strict contract), but for application code written by beginners it is almost always an unnecessary risk.
To feel the difference, here is an example:
package main
import "fmt"
func main() {
var x any = "go"
_ = x.(int) // panic: interface conversion: interface {} is string, not int
fmt.Println("unreachable")
}
When can you do this? Keep this criterion in mind: “I really want the program to crash if the type does not match, because that is a contract violation, and continuing is pointless.”
But in a learning project and in most business code, it is better to stick to the safe form with ok.
Mini table: safe vs unsafe assertion
To make the mental model easier to fix, here is a short table.
| Form | What it does | If the type does not match | When to use |
|---|---|---|---|
|
Tries to extract T | ok=false, v = zero value | Almost always in ordinary logic |
|
Extracts T “with no alternatives” | panic | Rarely: tests, strict internal contract |
3. Practical cases: results, interfaces, and errors
Rendering a command result without type switch
To avoid learning the tool “in the air”, let us tie it to our project. Imagine that we have a small console “task tracker” (let us call it tasky for convenience). At this stage of the course it is still simple: we execute commands and get a result that needs to be printed.
Sometimes a command returns one task, sometimes a list of tasks, sometimes just the string “done”. We want one function renderResult that accepts “anything” and prints it nicely.
For now we do not use type switch (that is a separate topic), but instead do a basic variant via several assertions in a row.
First, the data model:
package main
type Task struct {
ID int
Title string
Done bool
}
Now the rendering function via type assertion:
package main
import "fmt"
func renderResult(x any) {
if s, ok := x.(string); ok {
fmt.Println(s)
return
}
if t, ok := x.(Task); ok {
fmt.Printf("#%d %s (done=%v)\n", t.ID, t.Title, t.Done)
return
}
fmt.Printf("unknown result: type=%T value=%v\n", x, x)
}
And the check:
package main
func main() {
renderResult("ok") // ok
renderResult(Task{ID: 1, Title: "Go"}) // #1 Go (done=false)
renderResult(123) // unknown result: type=int value=123
}
Here it is important that the code reads like a “chain of attempts”: “if string — print string; if Task — print Task; otherwise — diagnose”. This is already a good working pattern, even before getting acquainted with type switch.
Assertion to an interface: “check behavior”, not “guess the type”
Now comes one of the most useful shifts in thinking: type assertion can be done not only to concrete types, but also to interfaces.
For example, the standard library fmt knows the interface:
type Stringer interface {
String() string
}
If a value implements String() string, then fmt can print it nicely. We can use this too: if the command result can “describe itself”, then we print it via String().
Add the method:
package main
import "fmt"
func (t Task) String() string {
status := " "
if t.Done {
status = "x"
}
return fmt.Sprintf("[%s] #%d %s", status, t.ID, t.Title)
}
Now renderResult can first check “isn’t this a fmt.Stringer?”:
package main
import (
"fmt"
)
func renderResult(x any) {
if s, ok := x.(fmt.Stringer); ok {
fmt.Println(s.String())
return
}
fmt.Printf("fallback: %T %v\n", x, x)
}
And an example:
package main
func main() {
renderResult(Task{ID: 2, Title: "Write code"}) // [ ] #2 Write code
}
Why is this cool? Because it is closer to the Go spirit: we work not with “magic types”, but with behavior. Our code has fewer “lists of specific structs”, and more “if you can do this — we act like this”.
Assertion to error interfaces: how to recognize a “special” error
Errors are one of the most common reasons for type assertion in real Go code. In the standard library, you can find the approach where an error may implement additional methods, and then it can be handled more intelligently.
We will not go into networking (we care about the mechanism right now), so let us model a situation: we have a function that returns error, and sometimes it is an error with an “extra property”.
Let us make a “temporary error” interface:
package main
type temporary interface {
error
Temporary() bool
}
Let us make an error type:
package main
type TempError struct{ msg string }
func (e TempError) Error() string { return e.msg }
func (e TempError) Temporary() bool { return true }
Now the handling:
package main
import "fmt"
func handle(err error) {
if err == nil {
return
}
if t, ok := err.(temporary); ok && t.Temporary() {
fmt.Println("temporary problem, try again") // temporary problem, try again
return
}
fmt.Println("fatal:", err.Error())
}
This has a very “Go-like” philosophy: instead of a huge exception hierarchy, we have small interfaces that can be checked precisely through type assertion.
4. Nuances: T vs *T, nil, and scope
Nuance T vs *T: why pointer and value are different worlds
Type assertion is sensitive to which concrete type is inside the interface: T or *T. These are not the same thing.
Let us compare:
package main
import "fmt"
type User struct{ Name string }
func main() {
u := User{Name: "Ann"}
p := &User{Name: "Bob"}
var x any = u
_, ok1 := x.(User)
_, ok2 := x.(*User)
fmt.Println(ok1, ok2) // true false
x = p
_, ok3 := x.(User)
_, ok4 := x.(*User)
fmt.Println(ok3, ok4) // false true
}
So “there is a value inside” and “there is a pointer inside” are two different cases. If you put User into an interface, then you need to extract User. If you put *User, then you need to extract *User.
Practical advice: if you design an API, try to be consistent — either you store values everywhere, or pointers everywhere. If you work with someone else’s API, just accept it as given and check the correct variant.
Nuance nil: why x == nil and “nil inside” are different stories
Type assertion often appears near nil, so let us carefully say it: an interface stores a pair (type, value). If the type exists, but the value is nil, the interface itself is not nil.
Here is the demonstration:
package main
import "fmt"
func main() {
var x any
fmt.Println(x == nil) // true
var p *int = nil
x = p
fmt.Println(x == nil) // false
fmt.Printf("%T %v\n", x, x) // *int <nil>
}
How is this related to type assertion? Directly: assertion to *int will succeed, because the type inside is *int, even if the value is nil.
package main
import "fmt"
func main() {
var p *int = nil
var x any = p
q, ok := x.(*int)
fmt.Println(ok) // true
fmt.Println(q == nil) // true
}
That is: “the type matched” (so ok = true), but “the value is empty” (so q == nil). And this is a normal situation.
A beginner mistake is to think that ok = true guarantees “there is a live object there”. No: ok only says “the type matches”.
Pattern “narrow block”: assertion inside if so as not to pollute scope
In Go there is a very nice style: declare v, ok := ... right inside if, so that v lives only where it is needed and does not interfere later.
package main
import "fmt"
func printID(x any) {
if t, ok := x.(Task); ok {
fmt.Println(t.ID) // print task ID
return
}
fmt.Println("no task here")
}
This style is valued because the scope is minimal: you do not keep variables “for the whole screen”, but localize them exactly in one condition. The code is easier to read, and there is less chance to accidentally use t where it no longer makes sense.
Mini diagram: how safe type assertion works “in your head”
Sometimes it is useful to imagine what the compiler/runtime does, in the form of a simple flowchart.
flowchart TD
A["x: interface (type+value)"] --> B{"inner type == T ?"}
B -->|yes| C["v = value of type T ok = true"]
B -->|no| D["v = zero value T ok = false"]
This diagram nicely explains two nuances at once: why ok is absolutely necessary, and why with ok = true the value can still be nil (if T is a pointer and nil is stored inside).
5. Typical mistakes when using type assertion
Mistake №1: use the unsafe form x.(T) “just in case”.
The problem is that “just in case” and panic do not get along well. In application logic, the unsafe form turns the ordinary situation “the wrong type came in” into a program crash. If this is not a strict contract, choose v, ok := ... and treat the ok == false branch as a normal scenario.
Mistake №2: ignore ok and work with v as if everything were fine.
When assertion fails, v becomes the zero value. This is especially tricky for numbers (0) and booleans (false): the program may “sort of work”, but make wrong decisions. Therefore ok is not a decorative flag, but a semantic part of the operation.
Mistake №3: confuse T and *T and wonder why ok is always false.
When you put a value into an interface, the concrete type T will be stored there. When you put a pointer — *T. Assertion does not make “guesses” or “auto-dereferencing”. If you are not sure, print %T and look at the real type inside.
Mistake №4: assume that ok == true means “the object is not nil”.
ok only says “the type matched”. If T is a pointer, the value inside may be nil, and that is a separate check. Often correct code looks like “assertion + nil check”, and that is normal.
Mistake №5: try to build a big “zoo of ifs” for dozens of types and then hate maintenance.
Type assertion is good when there are few checks or when you check “behavior” through interfaces (fmt.Stringer, temporary, etc.). If there become many types, readability drops: that is a sign that you need another form of branching by type. But the key idea here is not “type assertion is bad”, but “every tool has a scale at which it stays readable”.
GO TO FULL VERSION