From 261a781b152dc6daa0c4e910f341242235290c91 Mon Sep 17 00:00:00 2001 From: Ian Jackson Date: Mon, 5 Jun 2023 17:08:41 +0100 Subject: [PATCH] W --- src/main.rs | 31 ++++++++++++++++++++----------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/src/main.rs b/src/main.rs index b860f63..13d9400 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,9 +2,12 @@ use std::any::{Any,TypeId}; use std::sync::Arc; -pub trait HasPseudoMethods: Any + Send + Sync + 'static { +use downcast_rs::{DowncastSync, impl_downcast}; + +pub trait HasPseudoMethods: DowncastSync { fn cast_to_instance(&self, arc: Arc, tp: TypeId) -> Option>; } +impl_downcast!(sync HasPseudoMethods); /* pub trait HasPseudoMethodsExt { fn cast_to(&self) -> Option>; @@ -27,14 +30,15 @@ trait EatsFood { struct Frog; +impl HasFeet for Frog { + fn how_many_feet(&self) -> usize { 4 } +} + +/* impl EatsFood for Frog { fn favorite_food(&self) -> &'static str { "flies" } -} -/* -impl HasFeet for Frog { - fn how_many_feet(&self) -> usize { 4 } }*/ impl HasPseudoMethods for Frog { @@ -43,7 +47,8 @@ impl HasPseudoMethods for Frog { // table. I'm not sure if that's needed. fn cast_to_instance(&self, arc: Arc, tp: TypeId) -> Option> { if tp == TypeId::of::>() { - let arc: Arc = Arc::downcast::(arc); + let arc: Arc = DowncastSync::into_any_arc(arc); + let arc: Arc = Arc::downcast::(arc).unwrap(); let arc: Arc = arc.clone(); return Some(Box::new(arc)); /* } else if tp == TypeId::of::>() { @@ -59,10 +64,14 @@ fn main() { let frog = Arc::new(Frog); let erased_frog: Arc = frog as _; - let with_feet: Arc = *erased_frog.cast_to::>().unwrap(); - let eats_food: Arc = *erased_frog.cast_to::>().unwrap(); + let with_feet: Box = erased_frog.cast_to_instance( + erased_frog.clone(), + TypeId::of::>(), + ).unwrap(); + + let with_feet: Box> = with_feet.downcast().unwrap(); - println!("A frog has {} feet and eats {}.", - with_feet.how_many_feet(), - eats_food.favorite_food()) + println!("A frog has {} feet and eats .", + with_feet.how_many_feet(),/* + eats_food.favorite_food()*/) } -- 2.30.2