Macro nar_dev_utils::catch_flow

source ·
macro_rules! catch_flow {
    ( $($path:ident).+ $(; $($tail:tt)*)? ) => { ... };
    ( $value:expr => $($path:ident).+ $(; $($tail:tt)*)? ) => { ... };
    ( { $($value:tt)+ } => { $($f:tt)+ } ; $($arg:tt)* ) => { ... };
    ( { $($value:tt)+ } => { $($f:tt)+ } ) => { ... };
}
Expand description

用于将「流式追加」捕捉转换成「固定返回值」

  • 🎯首次应用于「基于String::push_str动态追加产生字符串」与「直接返回字符串」的转换中
    • 📌【2024-03-16 18:05:48】因解析器中应用广泛,目前暂不移除该用法

§示例

默认用法:生成String

use nar_dev_utils::catch_flow;

fn append(out: &mut String) {
    out.push_str("hello, ");
}

fn append_with(out: &mut String, with: &str) {
    out.push_str(with);
}

let caught = catch_flow!(append); // 默认用法:使用[`String::new`]生成一个新字串
let caught = catch_flow!(caught => append_with; "world!"); // 将捕获结果再次传入,并附加参数
assert_eq!(caught, "hello, world!");

同样可用于非字符串变量:

use nar_dev_utils::catch_flow;

fn add_one(n: &mut usize) {
    *n += 1;
}

let caught = catch_flow!(0 => add_one);
assert_eq!(caught, 1);