โ— Shell
clean mode source โ†—

rustpython_vm::match_class - Rust

[โˆ’][src]Macro rustpython_vm::match_class

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());