3 个不稳定版本
0.1.1 | 2021 年 12 月 20 日 |
---|---|
0.1.0 | 2021 年 12 月 5 日 |
0.0.0 | 2021 年 12 月 5 日 |
#1652 in Rust 模式
10KB
flow_control
用于常见控制流用例的声明性宏,例如 break
、continue
和 return
。
break_if
如果给定谓词评估为真,则从循环中退出。
use flow_control::break_if;
break_if!(predicate);
break_if!(predicate, label);
continue_if
如果给定谓词评估为真,则继续循环的下一个迭代。
use flow_control::continue_if;
continue_if!(predicate);
continue_if!(predicate, label);
return_if
如果给定谓词评估为真,则从函数中返回。
use flow_control::return_if;
return_if!(predicate);
return_if!(predicate, value);
示例
break_if
仅谓词
use flow_control::break_if;
let mut v = Vec::new();
for outer_n in 1..3 {
for inner_n in 1..5 {
break_if!(inner_n == 3);
v.push((outer_n, inner_n));
}
}
assert_eq!(
v,
vec![
(1, 1), (1, 2),
(2, 1), (2, 2),
]
);
谓词和标签
use flow_control::break_if;
let mut v = Vec::new();
'outer: for outer_n in 1..3 {
for inner_n in 1..5 {
break_if!(inner_n == 3, 'outer);
v.push((outer_n, inner_n));
}
}
assert_eq!(
v,
vec![(1, 1), (1, 2)],
);
continue_if
仅谓词
use flow_control::continue_if;
let mut v = Vec::new();
for outer_n in 1..3 {
for inner_n in 1..5 {
continue_if!(inner_n == 3);
v.push((outer_n, inner_n));
}
}
assert_eq!(
v,
vec![
(1, 1), (1, 2), (1, 4),
(2, 1), (2, 2), (2, 4),
]
);
谓词和标签
use flow_control::continue_if;
let mut v = Vec::new();
'outer: for outer_n in 1..3 {
for inner_n in 1..5 {
continue_if!(inner_n == 3, 'outer);
v.push((outer_n, inner_n));
}
}
assert_eq!(
v,
vec![
(1, 1), (1, 2),
(2, 1), (2, 2),
]
);
return_if
默认返回
use flow_control::return_if;
let mut v = Vec::new();
(|| {
for n in 1..10 {
return_if!(n == 5);
v.push(n)
}
})();
assert_eq!(v, vec![1, 2, 3, 4]);
返回指定值
use flow_control::return_if;
let get_value = || {
for n in 1..10 {
return_if!(n == 5, "early return");
}
return "return after loop";
};
assert_eq!(get_value(), "early return");