vir*_*tor 6 macros code-generation rust
我想创建一个setter/getter函数对,其中名称是基于共享组件自动生成的,但我找不到生成新名称的宏规则的任何示例.
有没有办法生成代码fn get_$iden()和SomeEnum::XX_GET_$enum_iden?
dto*_*nay 10
如果您使用 Rust >= 1.31.0,我建议您使用我的pastecrate,它提供了一种在宏中创建连接标识符的稳定方法。
macro_rules! make_a_struct_and_getters {
($name:ident { $($field:ident),* }) => {
// Define the struct. This expands to:
//
// pub struct S {
// a: String,
// b: String,
// c: String,
// }
pub struct $name {
$(
$field: String,
)*
}
paste::item! {
// An impl block with getters. Stuff in [<...>] is concatenated
// together as one identifier. This expands to:
//
// impl S {
// pub fn get_a(&self) -> &str { &self.a }
// pub fn get_b(&self) -> &str { &self.b }
// pub fn get_c(&self) -> &str { &self.c }
// }
impl $name {
$(
pub fn [<get_ $field>](&self) -> &str {
&self.$field
}
)*
}
}
};
}
make_a_struct_and_getters!(S { a, b, c });
Run Code Online (Sandbox Code Playgroud)
不,不是Rust 1.22.
如果你可以使用夜间建筑......
是的:concat_idents!(get_, $iden)这样就可以创建一个新的标识符.
但不是:解析器不允许在任何地方进行宏调用,因此您可能尝试执行此操作的许多地方都不起作用.在这种情况下,你很遗憾地靠自己.fn concat_idents!(get_, $iden)(…) { … }例如,不起作用.
我的mashup箱子提供了一种稳定的方式来创建可用于任何Rust版本> = 1.15.0的新标识符。
#[macro_use]
extern crate mashup;
macro_rules! make_a_struct_and_getters {
($name:ident { $($field:ident),* }) => {
// Define the struct. This expands to:
//
// pub struct S {
// a: String,
// b: String,
// c: String,
// }
pub struct $name {
$(
$field: String,
)*
}
// Use mashup to define a substitution macro `m!` that replaces every
// occurrence of the tokens `"get" $field` in its input with the
// concatenated identifier `get_ $field`.
mashup! {
$(
m["get" $field] = get_ $field;
)*
}
// Invoke the substitution macro to build an impl block with getters.
// This expands to:
//
// impl S {
// pub fn get_a(&self) -> &str { &self.a }
// pub fn get_b(&self) -> &str { &self.b }
// pub fn get_c(&self) -> &str { &self.c }
// }
m! {
impl $name {
$(
pub fn "get" $field(&self) -> &str {
&self.$field
}
)*
}
}
}
}
make_a_struct_and_getters!(S { a, b, c });
Run Code Online (Sandbox Code Playgroud)