"lifetime may not live long enough" error that occurs only with "dyn Trait"
โ Rust ๐ 2025-08-03 ๐ค surdeus ๐๏ธ 10Hello.
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
๐ท๏ธ Rust_feed