Macro fn_block::fn_expr [−][src]
macro_rules! fn_expr { ($return_type:ty : $body:expr) => { ... }; ($body:expr) => { ... }; }
This macro wraps a given rust code block into a closure and directly calls the closure. Optionally the return type of the closure can be specified first and separeted with a colon from the body expression.
Example without return type:
let o = Some("Foobar"); let s = fn_block!{{ let foo = o?.get(0..3); Some(foo?.to_lowercase()) }}; assert_eq!("foo", s.unwrap());
Example with return type:
use std::str::from_utf8; use std::error::Error; struct ConvertErr(); impl <T: Error> From<T> for ConvertErr { fn from(_: T) -> ConvertErr {ConvertErr()} } let s : &[u8] = &[0x0020,0x0034,0x0032]; let res_int = fn_expr!{ Result<u32,ConvertErr>: from_utf8(s)?.trim().parse::<u32>()?.into_ok() }.unwrap_or(0u32); assert_eq!(res_int, 42);
Note that the example use the trait IntoOk
,
defined in this crate.