5 releases
0.1.4 | Dec 2, 2023 |
---|---|
0.1.3 | Nov 28, 2023 |
0.1.2 | Nov 28, 2023 |
0.1.1 | Nov 28, 2023 |
0.1.0 | Nov 28, 2023 |
#2082 in Rust patterns
7KB
125 lines
scalar_map
map
for scalar types.
let num: Option<i32> = Some(42);
assert_eq!(num.map(|x| 42 - x), Some(0));
let num: i32 = 42;
assert_eq!(num.map(|x| 42 - x), 0);
let num: Option<i32> = Some(42);
assert_eq!(num.and_then(Option::Some), Some(0));
let num: i32 = 42;
assert_eq!(num.and_then(Option::Some), Some(0));
What does it solve
-
You can still keep
map
andand_then
intact even ifOption
is refactored out. -
You want
x.map(Mutex::new).map(Arc::new)
...instead of
Arc::new(Mutex::new(x))
Custom struct
Deriving
# Run this to add the `derive` feature
cargo add scalar_map --features derive
#[derive(Debug, PartialEq, ScalarMap)]
struct MyNum(i32);
let num = MyNum(42);
assert_eq!(num.map(|x| 42 - x.0).map(MyNum), MyNum(0));
Without deriving
#[derive(Debug, PartialEq)]
struct MyNum(i32);
impl ScalarMapExt for MyNum {}
let num = MyNum(42);
assert_eq!(num.map(|x| 42 - x.0).map(MyNum), MyNum(0));
Dependencies
~0–260KB