Trait tor_rpcbase::ObjectRefExt

source ·
pub trait ObjectRefExt {
    // Required method
    fn cast_to_trait<T: ?Sized + 'static>(&self) -> Option<&T>;
}
Expand description

Extension trait for dyn Object and similar to support convenient downcasting to dyn Trait.

You don’t need to use this for downcasting to an object’s concrete type; for that, use downcast_rs::DowncastSync.

§Examples

use tor_rpcbase::{Object, ObjectRefExt, templates::*};
use derive_deftly::Deftly;
use std::sync::Arc;

#[derive(Deftly)]
#[derive_deftly(Object)]
#[deftly(rpc(downcastable_to = "HasFeet"))]
pub struct Frog {}
pub trait HasFeet {
    fn num_feet(&self) -> usize;
}
impl HasFeet for Frog {
    fn num_feet(&self) -> usize { 4 }
}

/// If `obj` is a HasFeet, return how many feet it has.
/// Otherwise, return 0.
fn check_feet(obj: Arc<dyn Object>) -> usize {
    let maybe_has_feet: Option<&dyn HasFeet> = obj.cast_to_trait();
    match maybe_has_feet {
        Some(foot_haver) => foot_haver.num_feet(),
        None => 0,
    }
}

assert_eq!(check_feet(Arc::new(Frog{})), 4);

Required Methods§

source

fn cast_to_trait<T: ?Sized + 'static>(&self) -> Option<&T>

Try to cast this Object to a T. On success, return a reference to T; on failure, return None.

Object Safety§

This trait is not object safe.

Implementations on Foreign Types§

source§

impl ObjectRefExt for Arc<dyn Object>

source§

fn cast_to_trait<T: ?Sized + 'static>(&self) -> Option<&T>

Implementors§