2个版本
0.1.1 | 2022年4月13日 |
---|---|
0.1.0 | 2021年2月8日 |
#168 in 无标准库
115KB
84 行
此crate引入了when!
宏,它为if
/else if
/else
链提供了更好的语法。语法类似于match
。
(灵感来自kotlin)
[dependencies]
kiam = "0.1"
使用方法
使用方法类似于match
,但分支由布尔表达式保护,而不是模式
kiam::when! {
false => (),
true => (),
// ...
}
_
可以作为默认分支使用(在表达式位置使用when!
也是必需的)
let x = kiam::when! {
false => 0,
_ => 1,
};
assert_eq!(x, 1);
您还可以使用let <pat> =
来匹配模式,但与match
不同,您需要为每个模式提供一个表达式
let a = None;
let b = Some(17);
let fallible = || Err(());
let x = kiam::when! {
let Some(x) = a => x,
let Ok(x) = fallible() => x,
let Some(x) = b => (x as u32) + 1,
_ => 1,
};
assert_eq!(x, 18);
最后说明
- 您还可以使用不带括号的struct字面量进行比较(在
if
/else if
/else
链中不能这样做) - 您可以将布尔分支与模式匹配混合使用
- 只执行一个分支(不要与类似C语言中的
switch
混淆)
let mut x = 0;
kiam::when! {
let Ok(_) = Err::<(), _>(()) => x = 1,
true => x = 2,
true => x = 3,
let Some(n) = Some(42) => x = n,
};
assert_eq!(x, 2);
#[derive(PartialEq)]
struct Struct { a: i32 }
// This does not compile because of the ambiguity
if Struct { a: 0 } == Struct { a: 0 } {
// ...
}
#[derive(PartialEq)]
struct Struct { a: i32 }
kiam::when! {
// This, on the other hand, compiles fine
Struct { a: 0 } == Struct { a: 0 } => {
// ...
},
}