我是生锈新手。我正在尝试创建宏,它需要一个缓冲区,然后从中解码一些数据并创建给定的变量列表。如果发生错误,那么它应该打印错误并继续,因为我将在接收缓冲区的循环中调用它。像这样的东西:-
for bin_ref in bufs {
extract!( bin_ref anime &str episodes u32 season u32);
//if everything goes ok then do some cool stuff with
//above variables otherwise take next buf_ref
}
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?所以我采用了这种方法:-
#[macro_export]
macro_rules! extract {
( $buf:ident $($var:ident $typ:ty),* ) => {
$(
ext_type!( $buf $var $typ );
)*
};
}
#[macro_export]
macro_rules! ext_type {
( $buf:ident $var:ident &str ) => {
let mut $var : &str = ""; //some string specific function
println!("doing cool things with '{}' which is string ",$var);
};
( $buf:ident $var:ident u32 ) => {
let mut $var : u32 = 34; //some u32 specific function
println!("doing cool things with '{}' which is u32",$var);
}
}
Run Code Online (Sandbox Code Playgroud)
我有以下测试功能:-
fn macro_test() {
let mut bin_ref : &[u8] = &[0u8;100];
ext_type!(bin_ref anime &str); // works
ext_type!(bin_ref episodes u32 ); // works
extract!( bin_ref username &str, password &str ); // does not work. why ??
}
Run Code Online (Sandbox Code Playgroud)
当我编译这个时,我收到以下错误:-
error: no rules expected the token `&str`
--> src/easycode.rs:11:34
|
11 | ext_type!( $buf $var $typ );
| ^^^^ no rules expected this token in macro call
...
19 | macro_rules! ext_type {
| --------------------- when calling this macro
...
48 | extract!( bin_ref username &str, password &str );
| ------------------------------------------------- in this macro invocation
Run Code Online (Sandbox Code Playgroud)
为什么我不能直接传递$typ给ext_type!宏?从代码调用时它可以工作
宏的规则需要在末尾ext_type!添加文字标记&str和。u32这些文字标记无法$typ:ty匹配中的匹配片段extract!。为了成功地将文字标记与匹配的片段匹配,它必须是tt,ident或lifetime。
在这种情况下唯一有效的选项是tt,简单地说,它只是一个解析器标记。然而,一种类型通常由多个标记组成;一个例子&str,它由两个标记组成&,它由两个标记和str。因此,我们必须使用重复来完全捕获带有 s 的类型tt:$($typ:tt)+效果会很好。
然而,使用无限重复 withtt是有代价的—— att将匹配几乎所有内容,因此简单地替换$typ:tywith$($typ:tt)+是行不通的,因为$typ重复将捕获所有内容,直到宏调用结束!为了防止这种情况发生,我们必须在宏规则匹配器中对类型标记树进行定界,以阻止它消耗所有内容。以使调用稍微冗长为代价,将重复内容括在括号中将对我们很有帮助,并阻止令牌树完全匹配我们想要的位置。修改后的宏如下所示:
#[macro_export]
macro_rules! extract {
( $buf:ident $($var:ident ($($typ:tt)+)),* ) => {
$(
ext_type!( $buf $var $($typ)+);
)*
};
}
Run Code Online (Sandbox Code Playgroud)
注意替换$typ:ty请注意匹配器中的with(这是用括号括起来的标记树重复),以及转录器中的with($($typ:tt)+) 替换。$typ$($typ)+
宏规则调用如下:
extract!(bin_ref username (&str), password (&str), id (u32));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2393 次 |
| 最近记录: |