keypath 0.2.0

Derivable, type-safe Swift-style keypaths.
Documentation
  • Coverage
  • 61.54%
    16 out of 26 items documented2 out of 15 items with examples
  • Size
  • Source code size: 25.89 kB This is the summed size of all the files inside the crates.io package for this release.
  • Documentation size: 4.55 MB This is the summed size of all files generated by rustdoc for all configured targets
  • Ø build duration
  • this release: 13s Average build duration of successful builds.
  • all releases: 13s Average build duration of successful builds in releases after 2024-10-23.
  • Links
  • cmyr/keypath
    60 2 0
  • crates.io
  • Dependencies
  • Versions
  • Owners
  • cmyr

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