如何使用可变参数宏来调用嵌套构造函数? [英] How to use variadic macros to call nested constructors?
问题描述
我正在尝试在Rust中创建一个宏,以便我编写
I'm trying to create a macro in Rust that lets me write
make_list!(1, 2, 3)
代替
Node::new(1, Node::new(2, Node::new(3, None)))
应该适用于任意数量的参数",包括零.这是我到目前为止的内容:
which should work for an arbitrary number of "parameters" including zero. This is what I have so far:
macro_rules! make_list(
() => (
None
);
( $x:expr, $( $more:expr ),* ) => (
Node::new($x, make_list!( $( $more ),* ))
)
);
但出现以下错误:
error: unexpected end of macro invocation
--> src/main.rs:19:42
|
19 | Node::new($x, make_list!( $( $more ),* ))
| ^^^^^
我对此不太了解.据我所知,它应该有效.我做错了什么?
I can't make much sense of this. From what I can tell, it should work. What did I do wrong?
完整代码:
type List<T> = Option<Box<Node<T>>>;
struct Node<T> {
value: T,
tail: List<T>,
}
impl<T> Node<T> {
fn new(val: T, tai: List<T>) -> List<T> {
Some(Box::new(Node::<T> {
value: val,
tail: tai,
}))
}
}
macro_rules! make_list(
() => (
None
);
( $x:expr, $( $more:expr ),* ) => (
Node::new($x, make_list!( $( $more ),* ))
)
);
fn main() {
let _list: List<i32> = make_list!(1, 2, 3, 4, 5, 6, 7, 8, 9);
}
推荐答案
扩展错误:您只剩下一个值的情况,因此它写为make_list!(1)
.但是,没有规则可以匹配该规则,对于第二个规则,在使用表达式x
之后,需要一个逗号(未提供).
Expanding on the error: you get down to the case where there is only one value, and so it writes make_list!(1)
. However, there is no rule that will match that, for the second rule, after consuming the expression x
, wants a comma, which is not provided.
因此,您需要制作它,使其适用于make_list!(1)
,而不仅仅适用于make_list!(1,)
.为此,请在重复部分内添加逗号,如下所示:
So you need to make it so that it will work for make_list!(1)
and not just (in fact, just not) make_list!(1,)
. To achieve this, get the comma inside the repeating part, like this:
macro_rules! make_list(
() => (
None
);
( $x:expr $( , $more:expr )* ) => (
Node::new($x, make_list!( $( $more ),* ))
)
);
奖金:如果需要,您可以写make_list![1, 2, 3]
而不是make_list!(1, 2, 3)
.
Bonus: you can write make_list![1, 2, 3]
instead of make_list!(1, 2, 3)
if you want.
这篇关于如何使用可变参数宏来调用嵌套构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!