set_field: Rust derive macro for structs

Set fields on structs by string.

SetField trait

rust pub trait SetField<T> { fn set_field(&mut self, field: &str, value: T) -> bool; }

Example

```rust use set_field::SetField;

[derive(SetField)]

struct Foo { a: i32, b: Option, c: i32, } fn test() { let mut t = Foo { a: 777, b: None, c: 0 }; // return true on success: asserteq!(t.setfield("a", 888), true); // return true on success: asserteq!(t.setfield("b", Some(true)), true); asserteq!(t.a, 888); asserteq!(t.b, Some(true)); // return false on nonexistent field: asserteq!(t.setfield("d", 0), false); // return false on wrong type: asserteq!(t.setfield("b", 0), false); // won't compile: // asserteq!(t.setfield("a", 0.0), false); } ```

Expanded Foo struct from above

The SetField macro expands Foo into this:

rust struct Foo { a: i32, b: Option<bool>, c: i32, } impl SetField<i32> for Foo { fn set_field(&mut self, field: &str, value: i32) -> bool { match field { "a" => { self.a = value; true } "c" => { self.c = value; true } _ => false, } } } impl SetField<Option<bool>> for Foo { fn set_field(&mut self, field: &str, value: Option<bool>) -> bool { match field { "b" => { self.b = value; true } _ => false, } } }

Dependencies