Skip to main content

ensure

Macro ensure 

Source
macro_rules! ensure {
    ($cond:expr, $error_kind:expr, $fmt:expr $(, $args:expr)* $(,)?) => { ... };
}
Expand description

Return an Error from the current function unless a condition holds.

ensure!(cond, kind, fmt, args...) is bail!(kind, fmt, args...) when cond is false.

§Arguments

  • cond - The condition that must hold.
  • kind - The kind of the error.
  • fmt - The format string of the message.
  • args - The format arguments.

§Returns

Returns Err of the error from the enclosing function when cond is false, and does nothing otherwise.

§Examples

use tvm_ffi::{ensure, Result, VALUE_ERROR};

fn sqrt(x: f64) -> Result<f64> {
    ensure!(x >= 0.0, VALUE_ERROR, "sqrt of negative number {}", x);
    Ok(x.sqrt())
}

assert_eq!(sqrt(4.0)?, 2.0);
assert!(sqrt(-1.0).is_err());