Skip to main content

Crate lens

Crate lens 

Source
Expand description

Macro-powered lenses for immutable Rust data structures.

§Example

use lens::{Lens, RefLens, Lenses, lens};

#[derive(Clone, Lenses)]
struct Address {
    street: String,
}

#[derive(Clone, Lenses)]
struct Person {
    address: Address,
}

let person = Person {
    address: Address {
        street: "123 Needmore Rd".to_string(),
    },
};

let street_lens = lens!(Person.address.street);
assert_eq!(street_lens.get_ref(&person), "123 Needmore Rd");

let updated = street_lens.set(person, "666 Titus Ave".to_string());
assert_eq!(street_lens.get_ref(&updated), "666 Titus Ave");

Vector indexing is supported as well:

use lens::{Lens, RefLens, Lenses, lens};

#[derive(Clone, Lenses)]
struct Item {
    value: u32,
}

#[derive(Clone, Lenses)]
struct Container {
    items: Vec<Item>,
}

let container = Container {
    items: vec![Item { value: 1 }, Item { value: 2 }],
};

let item_lens = lens!(Container.items[1].value);
assert_eq!(*item_lens.get_ref(&container), 2);
let updated = item_lens.set(container, 7);
assert_eq!(updated.items[1].value, 7);

Macros§

compose_lens
Provides a shorthand for composing a series of lenses.
lens

Structs§

ComposedLens
Composes two Lenses.
LensPath
Describes a lens relative to a source data structure.
LensPathElement
An element in a LensPath.
VecLens
A lens over a single element within a Vec<T>.

Traits§

Lens
A lens offers a purely functional means to access and/or modify a field that is nested in an immutable data structure.
RefLens
A lens that allows the target to be accessed and mutated by reference.
ValueLens
A lens that allows the target to be accessed only by cloning or copying the target value.

Functions§

compose
Composes a Lens<A, B> with another Lens<B, C> to produce a new Lens<A, C>.
modify
Modifies the target of the lens by applying a function to the current value. This consumes the source. (This lives outside the Lens trait to allow lenses to be object-safe but still allow for static dispatch on the given closure.)
vec_lens
Returns a Lens over a single element at the given index for a Vec<T>.

Derive Macros§

Lenses
Handles the #[derive(Lenses)] applied to a struct by generating a Lens implementation for each field in the struct.