| Crates.io | kiam |
| lib.rs | kiam |
| version | 0.1.1 |
| created_at | 2021-02-08 23:29:25.431125+00 |
| updated_at | 2022-04-13 19:08:57.336304+00 |
| description | Better syntax for if/else chains (when!) |
| homepage | https://github.com/WaffleLapkin/kiam/ |
| repository | https://github.com/WaffleLapkin/kiam/ |
| max_upload_size | |
| id | 352548 |
| size | 124,133 |
This crate introduces when! macro which provides better syntax for
if/else if/else chains. The syntax is similar to match.
(idea is borrowed from kotlin)
[dependencies]
kiam = "0.1"
Usage is similar to the usage of match, but instead of patterns, branches are guarded by boolean expression:
kiam::when! {
false => (),
true => (),
// ...
}
_ can be used as a default branch (it's also required to use when! in expression possition):
let x = kiam::when! {
false => 0,
_ => 1,
};
assert_eq!(x, 1);
You can also use let <pat> = to match a pattern, but in difference with match you'll have to provide an expression for every pattern:
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);
Last notes:
if/else if/else chain)switch in C-like languages)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 } => {
// ...
},
}