Skip to main content

ObjectOps

Trait ObjectOps 

Source
pub trait ObjectOps {
    // Required methods
    fn is<T: 'static>(&self) -> bool;
    fn to<T: 'static>(self) -> Result<T, Object>;
    fn to_ref<T: 'static>(&self) -> Option<&T>;
}
Expand description

Conversion and downcasting helpers for owned reflective objects.

Implemented for Object, ObjectMut and SendObject. Owned conversion consumes the wrapper and returns the reflected value as an Object when the requested concrete type does not match, while borrowed conversion leaves the wrapper in place.

Required Methods§

Source

fn is<T: 'static>(&self) -> bool

Checks whether the object stores a T.

Source

fn to<T: 'static>(self) -> Result<T, Object>

Converts the boxed object into T, returning the reflected value as an Object when its concrete type does not match.

To try several target types, use Result::or_else to call to again on the returned Object, as shown in the example.

§Example
use typex::{Meta, ObjectOps, SendObject};

#[derive(Debug, Meta)]
#[typex(opaque)]
struct Count(u8);

#[derive(Debug, Meta)]
#[typex(opaque)]
struct Label(&'static str);

let describe = |object: SendObject| {
  object
    .to::<Count>()
    .map(|count| count.0.to_string())
    .or_else(|remaining| {
      remaining
        .to::<Label>()
        .map(|label| label.0.to_string())
    })
    .unwrap()
};

assert_eq!(describe(SendObject::new(Count(23))), "23");
assert_eq!(describe(SendObject::new(Label("hello"))), "hello");
Source

fn to_ref<T: 'static>(&self) -> Option<&T>

Borrows the boxed object as T, returning None when its type does not match.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§