Managed to make this run by adding lots of `'_`, need help understanding them

โš“ Rust    ๐Ÿ“… 2026-01-01    ๐Ÿ‘ค surdeus    ๐Ÿ‘๏ธ 1      

surdeus

From the recommendations in the previous post, I managed to make the code in that post run with better_any. However I ended up adding lots of '_ that I don't understand at all.

use better_any::*;

trait Trait<'a>: Tid<'a> {
    fn do_it(&self) -> Box<dyn Trait<'_> + '_>;
}

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

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

#[derive(Tid)]
struct B<'a>(&'a A);

impl<'a> Trait<'a> 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")
*/

What I know for sure is that the &A in B must outlive the B. I actually don't know how to type the trait defs correctly. :frowning: Because if I write this:

trait Trait<'a>: Tid<'a> {
    fn do_it(&self) -> Box<dyn Trait<'a>>;
}

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

I get this lifetime error:

error: lifetime may not live long enough (click for more details)

If I change it to '_:

trait Trait<'a>: Tid<'a> {
    fn do_it(&self) -> Box<dyn Trait<'_>>;
}

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

I get error with a help โ€œto declare that the trait object captures data from argument self, you can add an explicit '_ lifetime boundโ€:

error: lifetime may not live long enough (click for more details)

So... that's how I ended up with all the '_s.

Could someone explain them to me?

3 posts - 2 participants

Read full topic

๐Ÿท๏ธ Rust_feed