Crate keypath

Source
Expand description

Derivable references to arbitarily nested fields.

This crate contains a basic implementation of ‘keypaths’, a mechanism for creating paths of references to the properties of objects that can be used to get and set their underlying values.

The general idea and design is strongly influenced by keypaths in Swift.

To work with keypaths, types must implement the Keyable trait; in most cases this will be derived.

KeyPath instances can then be created with the keypath! macro.

§Examples

use keypath::{Keyable, KeyPath, keypath};

#[derive(Keyable)]
struct Person {
    name: String,
    friends: Vec<String>,
    size: Size,
}

#[derive(Keyable)]
struct Size {
    big: bool,
    heft: u8,
}

let mut person = Person {
    name: "coco".into(),
    friends: vec!["eli".into(), "nico".into(), "yaya".into()],
    size: Size { big: false, heft: 45 }
};

let first_friend: KeyPath<Person, String> = keypath!(Person.friends[0]);
let heft = keypath!(Person.size.heft);

assert_eq!(person[&first_friend], "eli");

// mutation:
person[&heft] = 101;
assert_eq!(person.size.heft, 101);

Modules§

internals

Macros§

keypath
Create a strongly-typed KeyPath.

Structs§

FieldError
KeyPath
A non-fallible keypath.

Enums§

FieldErrorKind

Traits§

Keyable
A trait for types that can be indexed with keypaths.

Derive Macros§

Keyable