如何在Rust中获取struct字段名?

时间:2016-05-10 14:00:14

标签: reflection rust introspection

Rust的Object.keys()是否有一些等同于JS的struct

我需要从结构字段名称生成CSV标题(我使用rust-csv)。

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()

1 个答案:

答案 0 :(得分:13)

Rust当前主要的元编程方法是via macros。在这种情况下,您可以捕获所有字段名称,然后添加一个返回字符串形式的方法:

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());
}

对于高级宏,请务必查看The Little Book of Rust Macros