keypath 0.2.0

Derivable, type-safe Swift-style keypaths.
Documentation

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);