pub trait ObjectArcExt {
// Required methods
fn cast_to_trait<T: ?Sized + 'static>(&self) -> Option<&T>;
fn cast_to_arc_trait<T: ?Sized + 'static>(
self,
) -> Result<Arc<T>, Arc<dyn Object>>;
}
Expand description
Extension trait for Arc<dyn Object>
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, ObjectArcExt, 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§
Sourcefn cast_to_trait<T: ?Sized + 'static>(&self) -> Option<&T>
fn cast_to_trait<T: ?Sized + 'static>(&self) -> Option<&T>
Try to cast this Arc<dyn Object>
to a T
. On success, return a reference to
T; on failure, return None.
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.