Ale*_*nts 9 reflection introspection rust
对于Rust的结构,是否有一些等效的JS的Object.keys()?
我需要从结构字段名称生成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()
Run Code Online (Sandbox Code Playgroud)
She*_*ter 14
Rust当前主要的元编程方法是通过宏.在这种情况下,您可以捕获所有字段名称,然后添加一个返回字符串形式的方法:
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());
}
Run Code Online (Sandbox Code Playgroud)
对于高级宏,请务必查看Rust Macros的小书.
| 归档时间: |
|
| 查看次数: |
4566 次 |
| 最近记录: |