liveBook · Manning

Set_hook

As explained in Learn Rust in a Month of Lunches

set_hook is a Rust standard-library function that installs a global panic hook.

set_hook installs a global panic hook that replaces Rust’s default panic output. It accepts a closure, so the program can choose what to print when a panic occurs. section 21.2

A small custom hook

std::panic::set_hook(Box::new(|info| { println!("Well, that didn't work: {info}"); })); panic!(); The closure receives PanicInfo, which can provide the panic message and location. Its payload can also be inspected and downcast when the panic carries a compatible value. section 21.2

fn main() {
    std::panic::set_hook(Box::new(|_| {
        println!("Oops, that didn't work.");
        println!("앗 뭔가 잘못 됐네요.");        #1
    }));
    
    panic!();
}

View a runnable example that replaces the default panic report with custom messages. section 21.2

How Learn Rust in a Month of Lunches covers it

How deep it goes
Explains closure registration, PanicInfo formatting, payload downcasting, and hook removal, but stops short of implementation internals.
Examples
Uses explicit panics, failed integer parsing, multilingual messages, formatted PanicInfo, and payload inspection.
What it assumes
Assumes basic Rust closures and panic behavior while introducing PanicInfo, Any, and payload downcasting during the explanation.
What you can do after
Operate/configure it by registering custom panic messages, printing PanicInfo, and inspecting compatible panic payloads.
How it connects
Connects panic!, panic hooks, PanicInfo, Any, payload downcasting, and take_hook.

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.