Type Assertions
The Two-Value Form
v, ok := i.(Type) attempts to extract the concrete value as the given type, setting ok to true on success or false (with v as the zero value) on failure -- this never panics, making it the safe default.
Note: Prefer the two-value form whenever the type isn't already guaranteed.
Example: The Two-Value Form
package main
import "fmt"
func main() {
var i interface{} = "hello"
s, ok := i.(string)
fmt.Println(s, ok)
n, ok := i.(int)
fmt.Println(n, ok)
}
Login to try C/C++/Java/PHP code in the editor
The Single-Value Form
i.(Type) without the ok flag returns just the value, but panics immediately if the interface doesn't actually hold that type -- useful when a mismatch would genuinely be a programmer error.
Note: Only use this form when you are certain of the underlying type, or you've already checked with a type switch.
Example: The Single-Value Form
package main
import "fmt"
func main() {
var i interface{} = 42
n := i.(int) // safe here, we know it's an int
fmt.Println(n + 8)
}
Login to try C/C++/Java/PHP code in the editor
Asserting to an Interface Type
A type assertion can also check whether a value satisfies a different, narrower interface than the one it's currently stored as, which is common when working with a general interface{} that might optionally support extra behavior.
Example: Asserting to an Interface Type
package main
import "fmt"
type Speaker interface {
Speak() string
}
type Dog struct{}
func (Dog) Speak() string { return "Woof" }
func main() {
var i interface{} = Dog{}
if s, ok := i.(Speaker); ok {
fmt.Println(s.Speak())
}
}
Login to try C/C++/Java/PHP code in the editor
- Using the single-value form (v := i.(Type)) without the ok flag, which panics at runtime if the assertion is wrong.
- Assuming a type assertion converts a value, when it's actually just checking/extracting the concrete type already stored inside the interface.
- Asserting to the wrong concrete type when a pointer versus value receiver distinction matters (e.g. *T vs T stored in the interface).
- A type assertion, i.(Type), extracts the concrete value stored in an interface value.
- The single-value form panics if the assertion fails -- use it only when you're certain of the type.
- The two-value form, v, ok := i.(Type), returns false instead of panicking on a mismatch.
- Type assertions are how you get back a concrete type after storing it in an interface{} or other interface.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: