Lesson 27 of 38 · Interfaces & Errors
Go Type Assertions and Type Switches
An interface hides the concrete type of the value inside it — that's the whole point. But sometimes you need that value back: an any that came from a config file, an error you want to inspect more closely, or a value that might also support some extra behaviour. Go's type assertions and type switches open the box.
Type assertions
v.(T) asserts that the interface value v holds a T and gives you that T:
var v any = "gopher"
s := v.(string)
fmt.Println(strings.ToUpper(s))
GOPHER
If you're wrong, the program panics:
n := v.(int) // panic: interface conversion: interface {} is string, not int
Assertions only work on interface values. If x is already a string variable, x.(int) doesn't even compile.
The comma-ok form
Ask for a second result and a failed assertion no longer panics: you get the zero value of T and false.
var v any = "gopher"
n, ok := v.(int)
fmt.Println(n, ok)
s, ok := v.(string)
fmt.Println(s, ok)
0 false
gopher true
It's the same , ok idiom you used to look up map keys. Use the single-result form only when a different type would be a bug in your program.
Type switches
To handle several possible types, use a type switch. The special syntax v.(type) is only allowed in a switch:
func Inspect(v any) string {
switch x := v.(type) {
case nil:
return "nothing"
case int:
return fmt.Sprintf("int, doubled: %d", x*2)
case string:
return fmt.Sprintf("string of length %d", len(x))
default:
return "something else"
}
}
func main() {
fmt.Println(Inspect(21), "|", Inspect("hey"), "|", Inspect(nil), "|", Inspect(2.5))
}
int, doubled: 42 | string of length 3 | nothing | something else
Inside each single-type case, x already has that type — x*2 compiles because x is an int there. case nil matches only when the interface itself is empty, and default catches every remaining type. Cases are checked from top to bottom.
Several types in one case
A case may list several types. Go can't know which one matched, so x keeps the interface type:
switch x := v.(type) {
case int, float64:
fmt.Println("a number:", x) // x is an any here: x*2 would not compile
}
When you need arithmetic, give each type its own case.
Does it also implement…?
You can assert to an interface type, too. That asks "does the value inside also have these methods?" — its concrete type doesn't matter:
type Celsius float64
func (c Celsius) String() string { return fmt.Sprintf("%.1f°C", float64(c)) }
func Show(v any) string {
if s, ok := v.(fmt.Stringer); ok {
return "stringer: " + s.String()
}
return "plain value"
}
func main() {
fmt.Println(Show(Celsius(21.5)), "|", Show(7))
}
stringer: 21.5°C | plain value
This is exactly how fmt.Println discovers your String method, and how code checks a value for optional extra behaviour.
Common mistakes
- Unchecked assertions on uncertain data:
v.(int)panics on the first unexpected value. Use comma-ok or a type switch. - Doing math in a multi-type case: in
case int, float64:the variable is still anany. - Expecting conversions: an assertion never converts.
any(42)holds anint, sov.(float64)fails, and the string"42"is not aninteither. - Switching instead of designing: if you keep switching over your own types, adding a method to an interface is usually cleaner.
Assignment
Describe(v any) stringdescribes a value:
v holds |
Result |
|---|---|
nil |
nil |
an int |
int 42 |
a float64 |
float64 2.5 (format with %g) |
a string |
string "hi" (quoted — use %q) |
a bool |
bool true |
a []int |
[]int of length 3 |
| anything else | unknown |
SumNumbers(values []any) float64adds up everyintandfloat64invaluesand ignores all other values.Talk(v any) stringreturns the result ofv'sSpeak()method ifvimplements theSpeakerinterface, and"..."otherwise.
Describe(42) // int 42
Describe("hi") // string "hi"
Describe(int64(42)) // unknown: an int64 is not an int
SumNumbers([]any{1, 2.5, "3", true}) // 3.5
Talk(Dog{Name: "Rex"}) // Rex says woof
Talk(Rock{}) // ...Premium lesson
Unlock the full Learn Go course
- All 38 lessons, bosses and quizzes — lifetime access
- One payment of $35, no subscription
- Finish within 30 days and claim $10.50 (30%) back
Want more than one course?
The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.
Keep learning
Need a quick reminder? The Go cheat sheet has every topic of Learn Go on one page.
Lesson last updated on .