Type assertions

December 5, 2023

Type assertions

For an expression x of interface type, but not a type parameter, and a type T, the primary expression

x.(T)

asserts that x is not nil and that the value stored in x is of type T. The notation x.(T) is called a type assertion.

For now, let’s look at some examples of type assertions that hold, and that don’t. In the next day or two, we’ll look at more details from the spec.

var i interface{} = int(3)

i.(int) // Holds; the dynamic type of `i` is `int`
i.(string) // Does not hold

type myString string

func (s myString) String() string {
	return string(s)
}

s := myString("Old MacDonald")

s.(myString) // Holds
s.(string) // Does not hold
s.(fmt.Stringer) // Holds; s implements the fmt.Stringer interface

Quotes from The Go Programming Language Specification Version of August 2, 2023


Share this

Direct to your inbox, daily. I respect your privacy .

Unsure? Browse the archive .

Get daily content like this in your inbox!

Subscribe