Rust宏可以创建新的标识符吗? [英] Can a Rust macro create new identifiers?
本文介绍了Rust宏可以创建新的标识符吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想创建一个setter/getter函数对,它们的名称是基于共享组件自动生成的,但是我找不到宏规则生成新名称的任何示例.
I'd like to create a setter/getter pair of functions where the names are automatically generated based on a shared component, but I couldn't find any example of macro rules generating a new name.
是否可以生成类似fn get_$iden()
和SomeEnum::XX_GET_$enum_iden
的代码?
Is there a way to generate code like fn get_$iden()
and SomeEnum::XX_GET_$enum_iden
?
推荐答案
我的 mashup
> 条板箱提供了一种稳定的方式来创建可用于任何Rust版本> = 1.15.0的新标识符.
My mashup
crate provides a stable way to create new identifiers that works with any Rust version >= 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 });
这篇关于Rust宏可以创建新的标识符吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文