How to get structure field names in Rust?

Is there some equivalent JS Object.keys () for Rust struct ?

I need something to generate CSV headers (I use rust-csv ) from the field names of the structure.

struct Export { first_name: String, last_name: String, gender: String, date_of_birth: String, address: String } //... some code let mut wrtr = Writer::from_file("/home/me/export.csv").unwrap().delimiter(b'\t'); wrtr.encode(/* WHAT TO WRITE HERE TO GET STRUCT NAMES as tuple of strings or somethings */).is_ok() 
+6
source share
1 answer

The current basic metaprogramming method in Rust through macros . In this case, you can capture all the field names, and then add a method that returns string forms from them:

 macro_rules! zoom_and_enhance { (struct $name:ident { $($fname:ident : $ftype:ty),* }) => { struct $name { $($fname : $ftype),* } impl $name { fn field_names() -> &'static [&'static str] { static NAMES: &'static [&'static str] = &[$(stringify!($fname)),*]; NAMES } } } } zoom_and_enhance!{ struct Export { first_name: String, last_name: String, gender: String, date_of_birth: String, address: String } } fn main() { println!("{:?}", Export::field_names()); } 

For advanced macros, be sure to check out the Little Macro Book of Rust .

+7
source

All Articles