This Rust library provides support for lenses, which are a mechanism in functional programming for focusing on a part of a complex data structure.
Add a dependency to your Cargo.toml
:
[dependencies]
pl-lens = "1.0"
Then, in your crate:
// To use the `derive(Lenses)` macro
use pl_lens::Lenses;
// To use the `lens!` macro
use pl_lens::lens;
// To bring trait methods like `get_ref` and `set` into scope
use pl_lens::{Lens, RefLens};
A Lens
can be used to transform a conceptually-immutable data structure by changing only a portion of the data. Let's demonstrate with an example:
#[derive(Lenses)]
struct Address {
street: String,
city: String,
postcode: String
}
#[derive(Lenses)]
struct Person {
name: String,
age: u8,
address: Address
}
let p0 = Person {
name: "Pop Zeus".to_string(),
age: 58,
address: Address {
street: "123 Needmore Rd".to_string(),
city: "Dayton".to_string(),
postcode: "99999".to_string()
}
};
assert_eq!(lens!(Person.name).get_ref(&p0), "Pop Zeus");
assert_eq!(lens!(Person.address.street).get_ref(&p0), "123 Needmore Rd");
let p1 = lens!(Person.address.street).set(p0, "666 Titus Ave".to_string());
assert_eq!(lens!(Person.name).get_ref(&p1), "Pop Zeus");
assert_eq!(lens!(Person.address.street).get_ref(&p1), "666 Titus Ave");
pl-lens
is distributed under an MIT license. See LICENSE for more details.