Type assertions
For an expression
x
of interface type, but not a type parameter, and a typeT
, the primary expressionx.(T)
asserts that
x
is notnil
and that the value stored inx
is of typeT
. The notationx.(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