type assertion
An expression such as value.(string) that gets the concrete value out of an interface, if it really holds that type.
In more detail
The two-result form text, ok := value.(string) sets ok to false instead of panicking when the type is wrong, so prefer it. The one-result form panics on a mismatch. Use assertions where data enters as any and convert to typed values quickly.
Example
seconds, ok := value.(int)Related terms
- type switch — A switch statement written switch v := value.(type) that picks a branch by the concrete type inside an interface value.
- empty interface — The interface with no methods, spelled any or interface{}, which every Go type satisfies.
- comma ok idiom — The Go pattern of receiving a second true-or-false result, as in value, ok := m[key], to learn whether an operation really found something.
- interface value — A value held in an interface variable, which carries two parts: the concrete type it really is and the value itself.
Taught in
- Type Assertions and the Empty Interface — Concurrent Systems Programming with Go