Alternatives to `dyn Any` `downcast` for types with non-static lifetimes that reference another type?

⚓ Rust    📅 2025-12-30    👤 surdeus    👁️ 3      

surdeus

The definition of A uses A(&'static str) instead of A<'a>(&'a str) in order to get compatible with Any. Even though, the way A and B operate makes it impossible (I believe) for B to be 'static.

use downcast_rs::{Downcast, impl_downcast};

trait Trait: Downcast {
    fn do_it(&self) -> Box<dyn Trait>;
}
impl_downcast!(Trait);

#[derive(Clone, Debug)]
struct A(&'static str);

impl Trait for A {
    fn do_it(&self) -> Box<dyn Trait> {
        println!("A: {}", self.0);
        Box::new(B(self))
    }
}

struct B<'a>(&'a A);

impl<'a> Trait for B<'a> {
    fn do_it(&self) -> Box<dyn Trait> {
        println!("B: {:?}", self.0);
        Box::new(self.0.clone())
    }
}

fn main() {
    let s = "aaaaa";
    let a: Box<dyn Trait> = Box::new(A(s));
    let b: Box<dyn Trait> = a.do_it();
    let a2: Box<dyn Trait> = b.do_it();
    let b2: Box<dyn Trait> = a2.do_it();
    b2.do_it();
}


/*
Expected output:
A: aaaaa
B: A("aaaaa")
A: aaaaa
B: A("aaaaa")
*/

Is there an alternative or workaround for this complex usecase? Like imagine A randomly returns B(&self) or C(&self), and C(a).do_it() randomly returns B(a) or C(a), etc.

Also please feel free to point out what else is wrong with the code.

2 posts - 2 participants

Read full topic

🏷️ Rust_feed