AnyKeypaths

Derive Macro AnyKeypaths 

Source
#[derive(AnyKeypaths)]
Expand description

Derives fully type-erased keypath methods.

AnyKeyPath is similar to Swift’s AnyKeyPath. It hides both the Root and Value types, making it useful for storing keypaths from different struct types in the same collection.

§Generated Methods

For each field field_name, generates:

  • field_name_r() - Returns an AnyKeyPath for readable access
  • field_name_w() - Returns an AnyWritableKeyPath for writable access
  • field_name_fr() - Returns an AnyKeyPath for optional fields
  • field_name_fw() - Returns an AnyWritableKeyPath 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 both root and value types.

§Examples

use keypaths_proc::AnyKeypaths;
use rust_keypaths::AnyKeyPath;

#[derive(AnyKeypaths)]
struct User {
    name: String,
    age: u32,
}

#[derive(AnyKeypaths)]
struct Product {
    price: f64,
}

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

let user = User {
    name: "Alice".to_string(),
    age: 30,
};

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