name-index

Crates.ioname-index
lib.rsname-index
version0.2.1
created_at2025-08-27 14:36:51.901119+00
updated_at2025-09-12 18:40:33.101039+00
descriptionLibrary for accessing struct fields by name at runtime
homepage
repositoryhttps://github.com/Fabillotic/name-index
max_upload_size
id1812770
size13,481
Evelyn (Fabillotic)

documentation

README

name-index

Library for accessing struct fields by name at runtime

Example:

use name_index::NameIndex;

#[derive(Default, NameIndex)]
struct MyStruct {
    // The #[index] attributes tells the derive macro to
    // start indexing all u32 fields from here on
    #[index]
    first: u32,
    second: u32,
    third: u32,
}

fn main() {
    let mut my_struct = MyStruct::default();

    // The name of the field we want to index
    // Might come from user input for example
    let name = "second";

    // Use NameIndex::get_ref_mut to get a mutable
    // reference to our field
    let field_ref: &mut u32 =
        NameIndex::get_ref_mut(&mut my_struct, name)
        .expect("second is a field of MyStruct");

    *field_ref = 5;

    assert_eq!(my_struct.second, 5);
}
Commit count: 29

cargo fmt