Type assertions in Go
Pulling a concrete type back out, safely or with a panic.
type Closer interface{ Close() error }
type File struct{ name string }
func (f File) Close() error { return nil }
func assertions(value any) (int, bool, bool) {
number, ok := value.(int)
_, isCloser := value.(Closer)
defer func() { _ = recover() }()
forced := value.(string) // panics unless it is a string
return number + len(forced), ok, isCloser
}
How it works
- The two-result form never panics: check the bool.
- The one-result form panics when the type is wrong.
- Asserting to an interface asks whether extra methods exist.
Keywords and builtins used here
anybooldefererrorfuncintinterfacelenrecoverreturnstringstructtype
The run, in numbers
- Lines
- 15
- Characters to type
- 355
- Tokens
- 94
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 54 seconds.
Step 2 of 2 in Dynamic types, step 9 of 19 in Interfaces & generics.