Type Assertions and Type Switches
Safe type assertions and switch patterns
Type Assertions
A type assertion extracts the concrete value from an interface. The syntax is x.(T):
package main
import "fmt"
func main() {
var i interface{} = "hello"
s := i.(string) // panics if wrong type
fmt.Println(s, len(s)) // hello 5
}Safe Two-Value Assertion
Use the comma-ok form to avoid panics on wrong types:
package main
import "fmt"
func main() {
var i interface{} = 42
s, ok := i.(string)
fmt.Println(s, ok) // "" false
n, ok := i.(int)
fmt.Println(n, ok) // 42 true
}All lessons in this course
- Defining and Implementing Interfaces
- Core Standard Library Interfaces
- Type Assertions and Type Switches
- Interface Composition and Best Practices