Type assertions

We briefly mentioned how type assertions work in Chapter 3, An Overview of Go. A type assertion is an operation that allows us to go from interface to concrete type and vice versa. It takes the following form:

# unsafe assertion
v := SomeVar.(SomeType)

# safe assertion
v, ok := SomeVar.(SomeType)

The first version is unsafe, and it assigns a value to a single variable.

Using assertion as an argument of a function also counts as unsafe. This type of operation panics if the assertion is wrong:

func main() {
var a interface{} = "hello"
fmt.Println(a.(string)) // ok
fmt.Println(a.(int)) // panics!
}

A full example is available here: https://play.golang.org/p/hNN87SuprGR.

The second version uses a Boolean a as second value, and it will show the success of the operation. If the assertion is not possible, the first value will always be a zero value for the asserted type:

func main() {
var a interface{} = "hello"
s, ok := a.(string) // true
fmt.Println(s, ok)
i, ok := a.(int) // false
fmt.Println(i, ok)
}

A full example is available here: https://play.golang.org/p/BIba2ywkNF_j.