Skip to main content

match_any

Macro match_any 

match_any!() { /* proc-macro */ }
Expand description

Match the runtime type of a value, the way match matches an enum.

The value is an Any, an AnyView, a managed reference or a MutationView. It is evaluated once and taken by value; write &value to keep it. Arms are tried in order, and the first arm whose type matches runs; a guard that is false moves on to the next arm. The last arm must be an unguarded _ => ..., since new types can be registered at any time.

  • Type(name) binds an owned value of Type, such as i64 or Array<Any>.
  • Type(ref name) borrows a managed reference, and NodeObj(ref name) borrows the object node, without changing its reference count.
  • MutationView<Type>(name) moves the in-place mode into a typed view.

Matching is strict: an i64 arm does not match a stored f64, and a value is never truncated. Type aliases and qualified paths may name Type. Typed MutationView arms do not match a Map, including a nested one; use MutationView<Any> for those. Ordinary Map<K, V> arms do match.

While an arm borrows the value, it must not modify an ffi.List or ffi.Dict that holds the value, which may be the borrow’s only owner.

§Examples

use tvm_ffi::{match_any, Any, Array};

fn kind(value: &Any) -> String {
    match_any! {
        value {
            i64(n) => format!("integer {n}"),
            tvm_ffi::String(s) => format!("string {}", s.as_str()),
            Array<Any>(arr) => format!("array of {} items", arr.len()),
            _ => "something else".to_string(),
        }
    }
}

assert_eq!(kind(&Any::from(42_i64)), "integer 42");
assert_eq!(kind(&Any::from(Array::from_vec(vec![1_i64, 2, 3]))), "array of 3 items");
assert_eq!(kind(&Any::from(1.5_f64)), "something else");