add field_lens! macro

main
annieversary 2021-11-11 22:32:59 +00:00
parent 0d91633f2b
commit 16d7190a1d
2 changed files with 26 additions and 0 deletions

12
src/lenses/fields.rs Normal file
View File

@ -0,0 +1,12 @@
#[macro_export]
macro_rules! field_lens {
($type:ident, $field:ident) => {
lens(
|v: $type| v.$field,
|mut u: $type, v| {
u.$field = v;
u
},
)
};
}

View File

@ -1,3 +1,5 @@
mod fields;
mod identity;
pub use identity::id;
@ -164,6 +166,18 @@ mod tests {
assert_eq!(l(hello), 8);
}
#[test]
fn can_make_lens_for_field() {
// making a lens
let l = crate::field_lens!(Hello, hey);
let hello = Hello { hey: 8 };
assert_eq!(l(hello), 8);
let hello = Hello { hey: 8 };
assert_eq!(l(hello, |v| v + 1), Hello { hey: 9 });
}
#[test]
fn can_make_lens_out_of_funcs() {
// making a lens