PartialKeypaths

Derive Macro PartialKeypaths 

Source
#[derive(PartialKeypaths)]
Expand description

Derives type-erased keypath methods with known root type.

PartialKeyPath is similar to Swift’s PartialKeyPath<Root>. It hides the Value type but keeps the Root type visible. This is useful for storing collections of keypaths with the same root type but different value types.

§Generated Methods

For each field field_name, generates:

  • field_name_r() - Returns a PartialKeyPath<Struct> for readable access
  • field_name_w() - Returns a PartialWritableKeyPath<Struct> for writable access
  • field_name_fr() - Returns a PartialOptionalKeyPath<Struct> for optional fields
  • field_name_fw() - Returns a PartialWritableOptionalKeyPath<Struct> for optional writable fields

§Type Erasure

The get() method returns &dyn Any, requiring downcasting to access the actual value. Use get_as::<Root, Value>() for type-safe access when you know the value type.

§Examples

use keypaths_proc::PartialKeypaths;
use rust_keypaths::PartialKeyPath;

#[derive(PartialKeypaths)]
struct User {
    name: String,
    age: u32,
    email: Option<String>,
}

// Usage:
let mut paths: Vec<PartialKeyPath<User>> = vec![
    User::name_r(),
    User::age_r(),
];

let user = User {
    name: "Alice".to_string(),
    age: 30,
    email: Some("alice@example.com".to_string()),
};

// Access values (requires type information)
if let Some(name) = paths[0].get_as::<User, String>(&user) {
    println!("Name: {}", name);
}