Skip to content
Justice Tech School

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

What does any mean?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.