Type Assertions and Switches
Check the dynamic type of an interface value with .(T) or a type switch.
Example
package main
import "fmt"
func main() {
for _, v := range []any{1, "go", 2.5} {
switch x := v.(type) {
case int:
fmt.Println("int", x+1)
case string:
fmt.Println("string", len(x))
default:
fmt.Println("other")
}
}
}Result
int 2 string 2 other
Exercise
Type switch.
switch x := v.()
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.