gpt4 book ai didi

error-handling - 宏匹配臂模式 “no rules expected the token ` if`”

转载 作者:行者123 更新时间:2023-12-03 08:09:03 25 4
gpt4 key购买 nike

所以我有这个宏来匹配多种错误类型的Box<dyn error::Error>

#[macro_export]
macro_rules! dynmatch {
($e:expr, $(type $ty:ty {$(arm $pat:pat => $result:expr),*, _ => $any:expr}),*, _ => $end:expr) => (
$(
if let Some(e) = $e.downcast_ref::<$ty>() {
match e {
$(
$pat => {$result}
)*
_ => $any
}
} else
)*
{$end}
);
}
直到我尝试添加火柴为止,一切都很好。当我尝试在模式中使用“if”语句时,它给我错误 no rules expected the token 'if'
let _i = match example(2) {
Ok(i) => i,
Err(e) => {
dynmatch!(e,
type ExampleError1 {
arm ExampleError1::ThisError(2) => panic!("it was 2!"),
_ => panic!("{}",e)
},
type ExampleError2 {
arm ExampleError2::ThatError(8) => panic!("it was 8!"),
arm ExampleError2::ThatError(9..=11) => 10,
_ => panic!("{}",e)
},
type std::io::Error {
arm i if i.kind() == std::io::ErrorKind::NotFound => panic!("not found"), //ERROR no rules expected the token `if`
_ => panic!("{}", e)
},
_ => panic!("{}",e)
)
}
};
有什么方法可以在我的模式匹配中使用匹配防护而不会出现 token 错误?

最佳答案

当然,即使我花了一个小时寻找解决方案,在我发布此问题后我也找到了答案。
正确的宏如下所示:

#[macro_export]
macro_rules! dynmatch {
($e:expr, $(type $ty:ty {$(arm $( $pattern:pat )|+ $( if $guard: expr )? => $result:expr),*, _ => $any:expr}),*, _ => $end:expr) => (
$(
if let Some(e) = $e.downcast_ref::<$ty>() {
match e {
$(
$( $pattern )|+ $( if $guard )? => {$result}
)*
_ => $any
}
} else
)*
{$end}
);
}
归功于 rust matches! source线244-251

关于error-handling - 宏匹配臂模式 “no rules expected the token ` if`”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63892562/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com