How to Use Type Assertions in Go

Use the value.(type) syntax to safely extract a concrete type from an interface value in Go.

Use a type assertion to extract a concrete type from an interface value by appending the target type in parentheses to the variable. If the type is incorrect or the interface is nil, the program panics unless you use the comma-ok idiom to check the result safely.

var i interface{} = 42
if v, ok := i.(int); ok {
    fmt.Println(v * 2)
} else {
    fmt.Println("not an int")
}