Macro gstd::bail

source ·
macro_rules! bail {
    ($res:expr, $msg:literal) => { ... };
    ($res:expr, $expl:literal, $fmtd:literal) => { ... };
    ($res:expr, $expl:literal, $fmt:literal $(, $args:tt)+) => { ... };
}
Expand description

Unwrap Result<T, E> to T if it is Ok(T) or panic with the provided message if the result is Err(E).

The message argument(s) can be either:

  • a string literal;
  • two string literals: the first is provided with panic when the program has been compiled in release mode, and the second is provided when the program is compiled in debug mode (either with --debug or --features=debug parameters);
  • a format string followed by arguments.

§Examples

Unwrap Ok(i32) value to i32:

use gstd::bail;

let result: Result<i32, ()> = Ok(42);
let value = bail!(result, "Unreachable as `result` is `Ok`");
assert_eq!(value, 42);

Panic when trying to unwrap the Err(&str) value:

let result: Result<(), &str> = Err("Wrong value");
// The next line will result in panic
let value = bail!(result, "We have an error value");

Panic with different messages for release and debug profiles:

let result: Result<(), &str> = Err("Wrong value");
// The next line will result in panic
let value = bail!(result, "Message in release mode", "Message in debug mode");

Panic with the formatted message string:

let result: Result<(), &str> = Err("Wrong value");
let a = 42;
// The next line will result in panic
let value = bail!(result, "Error", "a = {}", a);