GeezerVison is showing rustpython.github.io — rustpython_vm::match_class - Rust
macro_rules! match_class {
(match ($obj:expr) { _ => $default:expr $(,)? }) => { ... };
(match ($obj:expr) { $binding:ident => $default:expr $(,)? }) => { ... };
(match ($obj:expr) { $binding:ident @ $class:ty => $expr:block $($rest:tt)* }) => { ... };
(match ($obj:expr) { $binding:ident @ $class:ty => $expr:expr, $($rest:tt)* }) => { ... };
(match ($obj:expr) { $class:ty => $expr:block $($rest:tt)* }) => { ... };
(match ($obj:expr) { $class:ty => $expr:expr, $($rest:tt)* }) => { ... };
(match $($rest:tt)*) => { ... };
(@parse_match ($($target:tt)*) ({ $($inner:tt)* })) => { ... };
(@parse_match ($($target:tt)*) ($next:tt $($rest:tt)*)) => { ... };
}
Macro to match on the built-in class of a Python object.
Like match, match_class! must be exhaustive, so a default arm with
the uncasted object is required.
use num_bigint::ToBigInt;
use num_traits::Zero;
use rustpython_vm::VirtualMachine;
use rustpython_vm::match_class;
use rustpython_vm::obj::objfloat::PyFloat;
use rustpython_vm::obj::objint::PyInt;
use rustpython_vm::pyobject::PyValue;
let vm: VirtualMachine = Default::default();
let obj = PyInt::new(0).into_ref(&vm).into_object();
assert_eq!(
"int",
match_class!(match obj.clone() {
PyInt => "int",
PyFloat => "float",
_ => "neither",
})
);
With a binding to the downcasted type:
use num_bigint::ToBigInt;
use num_traits::Zero;
use rustpython_vm::VirtualMachine;
use rustpython_vm::match_class;
use rustpython_vm::obj::objfloat::PyFloat;
use rustpython_vm::obj::objint::PyInt;
use rustpython_vm::pyobject::PyValue;
let vm: VirtualMachine = Default::default();
let obj = PyInt::new(0).into_ref(&vm).into_object();
let int_value = match_class!(match obj {
i @ PyInt => i.as_bigint().clone(),
f @ PyFloat => f.to_f64().to_bigint().unwrap(),
obj => panic!("non-numeric object {}", obj),
});
assert!(int_value.is_zero());