我正在尝试在Rust中创建一个宏,让我可以编写:
make_list!(1, 2, 3)
替代
Node::new(1, Node::new(2, Node::new(3, None)))
这应该适用于任意数量的“参数”,包括零。到目前为止,我已经完成了以下内容:
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 ),* ))
| ^^^^^
我不太理解这段话的意思。从我所知道的来看,它应该能够运行。我做错了什么吗?
完整的代码:
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);
}