#[derive(Keypaths)]
{
// Attributes available to this derive:
#[Readable]
#[Writable]
#[Owned]
#[All]
}
Expand description
Derives keypath methods for struct fields.
This macro generates methods to create keypaths for accessing struct fields. By default, it generates readable keypaths, but you can control which methods are generated using attributes.
§Generated Methods
For each field field_name, the following methods are generated (depending on attributes):
field_name_r()- Returns aKeyPath<Struct, FieldType>for non-optional fieldsfield_name_w()- Returns aWritableKeyPath<Struct, FieldType>for non-optional fieldsfield_name_fr()- Returns anOptionalKeyPath<Struct, InnerType>for optional/container fieldsfield_name_fw()- Returns aWritableOptionalKeyPath<Struct, InnerType>for optional/container fieldsfield_name_fr_at(index)- Returns anOptionalKeyPathfor indexed access (Vec, HashMap, etc.)field_name_fw_at(index)- Returns aWritableOptionalKeyPathfor indexed mutable accessfield_name_o()- Returns aKeyPathfor owned access (when#[Owned]is used)field_name_fo()- Returns anOptionalKeyPathfor owned optional access
§Attributes
§Struct-level attributes:
#[All]- Generate all methods (readable, writable, and owned)#[Readable]- Generate only readable methods (default)#[Writable]- Generate only writable methods#[Owned]- Generate only owned methods
§Field-level attributes:
#[Readable]- Generate readable methods for this field only#[Writable]- Generate writable methods for this field only#[Owned]- Generate owned methods for this field only#[All]- Generate all methods for this field
§Supported Field Types
The macro automatically handles various container types:
Option<T>- Generates failable keypathsVec<T>- Generates keypaths with iteration supportBox<T>,Rc<T>,Arc<T>- Generates keypaths that dereferenceHashMap<K, V>,BTreeMap<K, V>- Generates key-based access methodsResult<T, E>- Generates failable keypaths forOkvariant- Tuple structs - Generates
f0_r(),f1_r(), etc. for each field
§Examples
ⓘ
use keypaths_proc::Keypaths;
#[derive(Keypaths)]
#[All] // Generate all methods
struct User {
name: String,
age: Option<u32>,
tags: Vec<String>,
}
// Usage:
let name_path = User::name_r(); // KeyPath<User, String>
let age_path = User::age_fr(); // OptionalKeyPath<User, u32>
let tags_path = User::tags_r(); // KeyPath<User, Vec<String>>
let user = User {
name: "Alice".to_string(),
age: Some(30),
tags: vec!["admin".to_string()],
};
// Read values
let name = name_path.get(&user);
let age = age_path.get(&user); // Returns Option<&u32>§Field-level Control
ⓘ
#[derive(Keypaths)]
struct Config {
#[Readable] // Only readable methods for this field
api_key: String,
#[Writable] // Only writable methods for this field
counter: u32,
#[All] // All methods for this field
settings: Option<Settings>,
}