Macros 是否可以对传递到宏中的标识符应用约束?
因为Rust还不支持in stable,所以可能需要将多个类似的标识符作为参数传入 这允许意外地传入错误的位置参数 是否有方法检查标识符是否符合一些基本规则,如“包含文本”、“以开头”、“以结尾”等Macros 是否可以对传递到宏中的标识符应用约束?,macros,rust,Macros,Rust,因为Rust还不支持in stable,所以可能需要将多个类似的标识符作为参数传入 这允许意外地传入错误的位置参数 是否有方法检查标识符是否符合一些基本规则,如“包含文本”、“以开头”、“以结尾”等 不可以,但通过向宏添加结构而不是只传递逗号分隔的名称,可以更容易地发现错误: macro_rules! my_macro { // Note: parameter must be in the right order; they're not general // keyword a
不可以,但通过向宏添加结构而不是只传递逗号分隔的名称,可以更容易地发现错误:
macro_rules! my_macro {
// Note: parameter must be in the right order; they're not general
// keyword arguments.
($name:ident, set=$set:ident, get=$get:ident, toggle=$toggle:ident)
=>
(
{}
)
}
fn main() {
// Correct usage
my_macro!(foo, set=my_set, get=my_get, toggle=my_toggle);
// Not right, but easier to spot with the keyword argument-style usage.
my_macro!(foo, set=my_set, get=my_toggle, toggle=my_get);
}
我使用了一些看起来像关键字参数的东西,但是你可以发明一些操作符,比如myu宏!(foo,=my_set,*my_get,!my_toggle)
如果这对您更有效的话
macro_rules! my_macro {
// Note: parameter must be in the right order; they're not general
// keyword arguments.
($name:ident, set=$set:ident, get=$get:ident, toggle=$toggle:ident)
=>
(
{}
)
}
fn main() {
// Correct usage
my_macro!(foo, set=my_set, get=my_get, toggle=my_toggle);
// Not right, but easier to spot with the keyword argument-style usage.
my_macro!(foo, set=my_set, get=my_toggle, toggle=my_get);
}