Type assertions of non-interface types

December 6, 2023

Yesterday we started on type assertions. Today we’ll look at some of the specific details, as they relate to type assertions to non-interface types. Tomorrow we’ll look at interface types.

Type assertions

More precisely, if T is not an interface type, x.(T) asserts that the dynamic type of x is identical to the type T.

Recall that variables of interface types contain a dynamic type, which represents the type that satisfies the interface:

var i interface{} = int(x) // variable i's dynamic type is int

A type assertion allows us to “get at” that dynamic type, effectively converting a type from an interface, back into that concrete type.

In this case, T must implement the (interface) type of x; otherwise the type assertion is invalid since it is not possible for x to store a value of type T.

So continuing from the example above:

i.(int) // Valid, since i's dynamic type is int
i.(float64) // Not valid; i's dynamic type is not float64

Of course there’s a limitation here. You can’t just arbitrarily assert from an interface to a concrete type. You must already know what concrete type you wish to convert to. This does limit the usefulness of type assertions like this somewhat, but there is some added flexibility we’ll see soon, that can make these assertions effectively conditional. And later, we’ll also learn about type switches, which give us even greater flexibility.

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 .