liveBook · Manning

Any

As explained in Learn Rust in a Month of Lunches

Any is a Rust standard-library trait for values that can support runtime type inspection and downcasting when they satisfy the required lifetime conditions.

Any is a Rust standard-library trait used to inspect a value’s type at runtime and try to recover a specific type. In a panic hook, the panic payload is held as dyn Any + Send. A hook can call downcast_ref::<&str>() to ask, “Is this payload a borrowed string?” If it is, the call returns a reference to that string; otherwise, it returns None. section 21.2

fn main() {
    std::panic::set_hook(Box::new(|info| {
        if let Some(payload) = info.payload().downcast_ref::<&str>() {
            println!("{payload}");    
        } else {
            println!("No payload!");
        }        
    }));
    panic!("Oh no");
}

The hook prints the payload when downcast_ref::<&str>() succeeds and prints “No payload!” otherwise. This demonstrates a type check, not a guarantee that every panic has a string payload. section 21.2

Watch the capitalization: Any is a trait; iterator .any() is a different API that checks whether any item meets a condition. section 21.2 section 9.1.3

How Learn Rust in a Month of Lunches covers it

How deep it goes
Shows dyn Any + Send and a downcast_ref::<&str>() check, but does not explain trait implementation or lifetime requirements.
Examples
Shows a panic hook that prints a borrowed-string payload or “No payload!” when the downcast fails.
What you can do after
Apply it via std::panic::set_hook to attempt downcast_ref::<&str>() on a panic payload.
How it connects
Connects trait objects and downcasting to panic payloads and panic hooks.

Also explained in

Compare how 2 books explain any →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.