field_accessor
With this procedural macro, you can dynamically get and update a field of the struct by a String type variable.
It can be good for you if you don't know which field you want when compiling. The functionality is similar to python's getattr, setattr.
Installation
[dependencies]
field_accessor = "0"
About this macro
This macro provides the four methods for structs. Only for get, set, to deal with different types of each field, I defined GetterSetter<T> trait and implemented it for each type.
//implement for each type
etc...
get
;
It returns a field's value. Note that you need to specify the return type.
get_mut
;
Returns a mutable reference to the field corresponding to the field_string.
set
;
It updates a field's value.
take
;
Replaces a field's value with the default value of T, returning the previous field's value.
swap
;
Swaps the values at two fields, without deinitializing either one.
replace
;
Moves src into the field, returning the previous field's value.
getenum
;
It returns a field's value like as get method, but the return type is enum. This method is helpful when field types vary. I will explain about enum later.
getstructinfo
;
You can extract a struct's field names, types, and a struct name.
Usage and Example

use FieldAccessor;
output
"Ken"
4
10
This code is generated at compiling.
Known issues
You need to specify the data type of the returned value. If it is not given, the compiler cannot infer the type. This restriction reduces the convenience of using this macro.
let mut dog = Dog ;
let fields = vec!
for field_name in fields.into_iter;
This code raises an error.
let fieldvalue = dog.get(&field_name).unwrap();
---------- ^^^ cannot infer type for type parameter `T` declared on the trait `GetterSetter`
|
consider giving `fieldvalue` the explicit type `&T`, where the type parameter `T` is specified
A workaround is to replace get with getenum. This macro defines (struct name)FieldEnum behind the scenes for you like below.
You can use this as a return type. With this enum you can get any field's value without concerning a field's type.
let mut dog = Dog ;
let fields = vec!;
let mut fieldvalues: = vec!;
for field_name in fields.into_iter;
assert_eq!;
assert_eq!;
Getting struct's information
You can get the information of the struct with (field name)StructInfo by calling getstructinfo.
Definition of (field name)StructInfo
Example
let info = dog.getstructinfo;
println!;
for i in info.field_names.iter
output
DogStructInfo { field_names: ["name", "age", "life_expectancy"], field_types: ["String", "u32", "u32"], struct_name: "Dog" }
name("Jiro")
age(4)
life_expectancy(10)
Author
Tomohiro Endo (europeanplaice@gmail.com)