"lifetime may not live long enough" error that occurs only with "dyn Trait"

โš“ Rust    ๐Ÿ“… 2025-08-03    ๐Ÿ‘ค surdeus    ๐Ÿ‘๏ธ 10      

surdeus

Warning

This post was published 122 days ago. The information described in this article may have changed.

Hello.

This code compiles:


fn test<'a>(s: Option<&'a mut Box<u32>>) {
    consume(s.map(|x| x.as_mut()));
}

fn consume<'a>(s: Option<&'a mut u32>) {}

But this code doesnโ€™t:


trait Test {}

fn test<'a>(s: Option<&'a mut Box<dyn Test>>) {
    // error: lifetime may not live long enough
    //     |
    // 167 | fn test<'a>(s: Option<&'a mut Box<dyn Test>>) {
    //     |         -- lifetime `'a` defined here
    // 168 |     consume(s.map(|x| x.as_mut()));
    //     |                       ^^^^^^^^^^ returning this value requires that `'a` must outlive `'static`
    consume(s.map(|x| x.as_mut()));
}

fn consume<'a>(s: Option<&'a mut dyn Test>) {}

The only difference is the u32 was replaced with dyn Trait.

Why the code doesnโ€™t compile? Why it matters if it is dyn Trait or u32 ?

Thanks you!

5 posts - 3 participants

Read full topic

๐Ÿท๏ธ Rust_feed