Trait AnyFieldAccess

Source
pub trait AnyFieldAccess: Any {
    // Required methods
    fn field_as_any(&self, field: &str) -> Option<&dyn Any>;
    fn field_as_any_mut(&mut self, field: &str) -> Option<&mut dyn Any>;
    fn field_names(&self) -> &'static [&'static str];
}
Expand description

Low-level struct field access.

In most cases it is more convenient to use the methods of the FieldAccess trait which has a blanket implementation for any type implementing AnyFieldAccess.

Consider automatically implementing it via #[derive(FieldAccess)] for structs where you need dynamic field access.

Required Methods§

Source

fn field_as_any(&self, field: &str) -> Option<&dyn Any>

Provides an immutable reference to a struct field.

Returns Some(_) if the field is accessible, otherwise None.

§Example
use field_access::{AnyFieldAccess, FieldAccess};

#[derive(FieldAccess)]
struct Foo {
    a: u8
}

let foo = Foo { a: 1 };
let field = foo.field_as_any("a");

assert!(field.is_some());
assert_eq!(field.unwrap().downcast_ref::<u8>(), Some(&1));
Source

fn field_as_any_mut(&mut self, field: &str) -> Option<&mut dyn Any>

Provides a mutable reference to a struct field.

Returns Some(_) if the field is accessible, otherwise None.

§Example
use field_access::{AnyFieldAccess, FieldAccess};

#[derive(FieldAccess)]
struct Foo {
    a: u8
}

let mut foo = Foo { a: 1 };

if let Some(field) = foo.field_as_any_mut("a") {
    if let Some(value) = field.downcast_mut::<u8>() {
        *value = 2;
    }
}

assert_eq!(foo.a, 2);
Source

fn field_names(&self) -> &'static [&'static str]

Provides the names of all accessible fields.

The field name order is undefined and should not be relied upon.

§Example
use field_access::{AnyFieldAccess, FieldAccess};

#[derive(FieldAccess, Default)]
struct Foo {
    a: u8,
    b: bool,
}

let foo = Foo::default();

assert_eq!(foo.field_names(), &["a", "b"]);

Implementors§