【发布时间】:2020-08-26 02:29:45
【问题描述】:
我正在尝试制作一个宏来生成具有新函数实现的结构。新函数需要根据字段的类型调用函数,并将返回值作为字段值。
新的实现最终应该像这样工作:
struct foo {
test: i32,
other: String,
}
impl foo {
fn new() -> Self {
foo {
test: get_i32(),
other: get_string(),
}
}
}
这是我当前的代码:
macro_rules! test {
(struct $name:ident { $($fname:ident : $ftype:ty),* }) => {
#[derive(Debug)]
pub struct $name {
$(pub $fname : $ftype),*
}
impl $name {
fn new(mut v: Vec<u8>) -> Self {
$name {
$($fname : ),*
}
}
}
};
}
我尝试过添加匹配语句,但它给出了不兼容的武器类型错误。
impl $name {
fn new(mut v: Vec<u8>) -> Self {
$name {
$($fname : match &stringify!($ftype)[..] {
"i32" => get_i32(),
"String" => get_string(),
}),*
}
}
}
谢谢。
【问题讨论】:
-
您尝试放置匹配语句;你能告诉我们你尝试了什么吗?现在很难说出你的问题到底是什么。
-
@Frxstrem 我添加了我尝试进行匹配的方式,但它给出了错误:“
matcharm 的类型不兼容”和“预期i32,找到结构std::string::String”。跨度>
标签: rust rust-macros