Macro tear::tear_if [−][src]
Explicit if
statement with early return
Description
tear_if! { cond, // <- NB: it's a comma
do_things();
v // Return value
}
If cond is true, it executes the statements in its body and returns its value (v here). It’s basically an early return without the return statement at the end.
tear_if! { let pat = expr,
do_things();
v
}
You can also use the pattern matching if let
.
Examples
Early return a value: recursively computing the length of a slice.
fn len (v: &[i32]) -> usize { // Base case tear_if! { v.is_empty(), 0 as usize } // Recursion 1 + len(&v[1..]) }
Handle simple cases: printing help in a command line utility
use std::env; fn main() { let args: Vec<String> = env::args().collect(); tear_if! { args.contains(&String::from("--help")), println!("No help available.") } println!("Greetings, human!"); }
Use patterns like if let
fn add_five(x: Option<i32>) -> i32 { tear_if! { let None = x, 0 } x.unwrap() + 5 } assert_eq![ add_five(Some(2)), 7 ]; assert_eq![ add_five(None), 0 ];