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::{decl_object, Object, ObjectRefExt};
use std::sync::Arc;
pub struct Frog {}
pub trait HasFeet {
fn num_feet(&self) -> usize;
}
impl HasFeet for Frog {
fn num_feet(&self) -> usize { 4 }
}
// Have `Frog` implement Object and declare that it can be
// downcast to HasFeet.
decl_object!{ Frog : [HasFeet] }
/// If `obj` is a HasFeet, return how many feet it has.
/// Otherwise, return 0.
fn check_feet(obj: Arc<dyn Object + 'static>) -> 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§
sourcefn cast_to_trait<T: ?Sized + 'static>(&self) -> Option<&T>
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.