Unwrap inner type when enum variant is known. From Stack overflow.
rust
/// 每个人承担自己的风险!
#[macro_export]
macro_rules! risk {
($expression:expr, $pattern:pat => $extracted_expression:expr) => {
match $expression {
$pattern => $extracted_expression,
_ => unreachable!(),
}
};
}
Example:
rust
enum Type {
I32(i32),
I64(i64),
F32(f32),
F64(f64)
}
fn fun() -> Type {
/// ... ...
}
let i = risk!(fun(), Type::I32(i) => i);
也许 if let
也是一个解决方案。
rust
enum Type {
I32(i32),
I64(i64),
F32(f32),
F64(f64)
}
fn fun() -> Type {
/// ... ...
}
if let Type::I32(i) = func() { i } else { unreachable!() }
实际上跟 risk!()
宏一样。不过既然能玩梗
每个人承担自己的风险! ↩︎