This does not make sense (error borrowed value does not live long enough)
⚓ Rust 📅 2026-05-24 👤 surdeus 👁️ 2type or paste code here
fn main() {
let v = vec![0usize];
type T2 = Box<dyn Fn()>;
let f = || -> T2 {
Box::new(|| {
let j2 = &v;
})
}; //this doesn't
let f2 = || -> Box<dyn Fn()> {
Box::new(|| {
let j2 = &v;
})
}; //this works
}
0 references | ▶ Run | ⚙ Debug
fn main() {
▏ let v = vec![0usize]; ■ binding `v` declared here
▏ type T2 = Box<dyn Fn()>;
▏ let f = || -> T2 { ■■■ unused variable: `f`
▏ ▏ Box::new(|| { ■ returning this value requires that `v` is borrowed for `'static`
▏ ▏ ▏ let j2 = &v; ■■■ `v` does not live long enough borrowed value does not live long enough
▏ ▏ })
▏ }; //this doesn't
▏ let f2 = || -> Box<dyn Fn()> { ■■ unused variable: `f2`
▏ ▏ Box::new(|| {
▏ ▏ ▏ let j2 = &v; ■■ unused variable: `j2` `#[warn(unused_variables)]` (part of `#[warn(unused)]`) on by default
▏ ▏ })
▏ }; //this works
} ■ `v` dropped here while still borrowed
2 posts - 2 participants
🏷️ Rust_feed