Boxing objects with bounded lifetimes

This thread is a follow-up question to an answer from @Yandros in this other (now closed) thread: Box with a trait object requires static lifetime? - #2 by Yandros

His code is here:

struct Holder<'lifetime> {
    objects: Vec<Box<dyn Object + 'lifetime>>,
}

impl<'lifetime> Holder<'lifetime> {
    fn add_object<T : Object + 'lifetime> (
        self: &'_ mut Self,
        object: T,
    )
    {
        self.objects
            .push(Box::new(object))
        ;
    }
}

But when I change Object to std::any::Any, now the compiler isn't cool about the lifetimes anymore. :frowning:

So, having no idea what the Object trait is, I figured I'd try implementing it. But I can't seem to figure out what methods it requires and the compiler usually tells me, but not this time.

I found lots of documentation about "trait objects", but the only thing I found about the "Object trait" was this: object::Object - Rust, and compiled machine code, aka "binary objects" and the "object files" that store them, are definitely unrelated. :frowning:

My core question is how to make it so I can box up bounded lifetimes, but this "Object trait" red herring has me really confused.

Thanks in advance for any replies. I'm sure I'll be smacking my forehead really hard when I hear what I'm doing wrong.

There is no trait named Object in the rust standard library. Reading that thread, I would assume Object is just some random trait in @frostfortune's codebase which they did not include in their post. If you want to run their code, could you just include trait Object {} like @Yandros did in their answer?

As for this:

This is because Any is defined as

pub trait Any: 'static { ... }

In other words, it requires 'static regardless of any other lifetime annotations.

2 Likes

D'oh. I knew I'd be smacking my forehead. I completely didn't see the top line where he defined the trait because I was focussed on making sure I was following his use of lifetime annotations.
Inattentional blindness - Wikipedia

When I replace std::any::Any with a custom nothing-trait, everything falls into place!

Thank you for putting up with my confusion.

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.