mdawar.dev

A blog about programming, Web development, Open Source, Linux and DevOps.

Go - Type Assertions

Syntax

The expression x.(T) is called a type assertion.

go
// Assert that `x` is not nil and is of type `T`.
// If `T` is an interface, assert that `x` implements `T`.
x.(T)

Usage

go
// Interface value.
var i any = "hello" // any is alias for interface{}

// Assert that the interface value is of type `string`
// and assign the undelying value to the variable `s`.
s := i.(string) // "hello"

// If the interface does not hold the type, the statement will trigger a panic.
n := i.(int) // runtime panic

// A type assertion can return 2 values, the underlying value and a boolean
// which will be `true` if the assertion holds.
// If the assertion does not hold, the boolean will be `false` and the value
// of the assigned variable will be the zero value of the tested type.
s, ok := i.(int) // 0, false (no runtime panic)