Rust Reference ยท Macros
Rust unreachable!, todo! and unimplemented!
Reference for unreachable!, todo! and unimplemented! in Rust: marking code paths, their panic messages, the never type and when to use each one.
These three macros all panic, and all have the never type !, so they fit anywhere an expression is needed. They differ in what they tell the reader. unreachable!() says "this can never run; if it does, there is a bug". todo!() says "I will write this later". unimplemented!() says "this is deliberately not provided (yet)".
Each accepts an optional format string and arguments like println!.
_ => unreachable!("remainder is always 0, 1 or 2"), fn later() -> u32 { todo!() }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
unreachable!(); unreachable!("message {}", value); todo!(); todo!("message"); unimplemented!(); unimplemented!("message {}", value);
| Macro | Panic message starts with |
|---|---|
unreachable!() |
internal error: entered unreachable code (plus : your message) |
todo!() |
not yet implemented (plus : your message) |
unimplemented!() |
not implemented (plus : your message) |
Returns: never (!). Panics: always, when executed.
Usage notes
todo!placeholders let a half-written program compile. Search fortodo!before you ship; Clippy has atodolint you can enable.unreachable!is a claim, not a hint to the optimizer. If you are wrong, you get a clean panic, not undefined behavior. For the unsafe, optimizer-trusting version seestd::hint::unreachable_unchecked, which is undefined behavior when reached.- Prefer types over
unreachable!. If you can restructure so the impossible case cannot be expressed (for example by using an enum), do that. unimplemented!suits trait methods that a type deliberately does not support. Returning an error is friendlier if callers might hit it.- Never type.
let x: u32 = todo!();compiles, and unused code after it produces a warning. - Pick a descriptive message for
unreachable!so the eventual bug report says why you thought the path was impossible.
Related
panic!,match,assert!, Panic, unwind and abort- Lessons: Panics, Enums and match