Why does T need 'static in Box<dyn Trait>

I have some code were I want to share a Read + Seek object between threads and memory.
However, when I want to return (to fullfill a trait in the rust-vfs crate), I need to rust a Box<dyn VPath> . I do a clone of the actual struct, that contain a PathBuf and an Arc (that contain another Arc<Mutex>). The compiler dont accept this, as it can be seen with this code: link to the rust playground

It work if, as suggested by the compiler, I add 'static to the generic ( working version ). I have however no idea what does this 'static mean in the generic context, a not being a static, as I can modify it without using unsafe code. Can someone indicate me what this mean ?

What 'static means, when used as a bound on a type, is that the type does not contain any fields with references that have non-'static lifetimes. For example, if you define a struct as follows:

struct Foo<'a> {
    x : &'a [u8]
};

Then, unless you are borrowing something static, it is not the case that Foo<'a> : 'static, but we do have that Foo<'a> : 'a because it doesn't contain any references that live shorter than 'a. A struct without references is always 'static.

In your case, the problem comes from the fact that trait objects are implicitly 'static by default, so Box<dyn Trait> is equivalent to Box<dyn Trait + 'static. The thing you put in the Box therefore needs to be 'static. You can specify a different lifetime using + 'a if you want, but you need the same bound on the generic input to the function.

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