Use `Any` to recover a concrete type from a trait object when needed. Add an `as_any` method returning `&dyn Any`, then use `downcast_ref` to check for a concrete type; it returns `Some` when the type matches. section 2.2.6
Any
The Rust Any trait enables runtime type identification and checked conversion to a concrete type for suitable values.
How Idiomatic Rust covers it
- How deep it goes
- Demonstrates `as_any` and `downcast_ref` without further implementation detail.
- Examples
- Checks trait objects for `MyStruct1` or `MyStruct2` and calls their concrete methods.
- What it assumes
- Assumes familiarity with trait objects and trait implementations.
- What you can do after
- Apply checked downcasting with `as_any` and `downcast_ref`.
- How it connects
- Connects `Any` with trait objects and dynamic dispatch.
Also explained in
-
Learn Rust in a Month of LunchesAny is a Rust standard-library trait for values that can support runtime type inspection and downcasting when they satisfy the required lifetime conditions.
Compare how 2 books explain any →
Related concepts
- short-circuit evaluationuses · Short-circuit evaluation is an evaluation strategy that skips remaining operands or processing when the result is already determined.
- findcontrasts with · A find operation searches a collection for the first element or entry matching a value or predicate and returns it, or indicates that no match exists.
- downcast_refproduces · downcast_ref is an operation that attempts to obtain a shared reference to an interface value as a specified concrete type.
- iteratoruses · An iterator is an object or abstraction that provides successive values from a sequence or data source through a traversal protocol.
- panicuses · A panic is a runtime failure mechanism that abruptly stops ordinary execution when an unrecoverable error or violated assumption prevents safe continuation.
This explainer was generated by Manning's knowledge graph from the text of Idiomatic Rust. The section links point to the parts of the book it draws on.

