Lifetime issue with associated types
โ Rust ๐ 2025-10-23 ๐ค surdeus ๐๏ธ 4Hello, I want to have State that I know will never borrow from View, but I can't convince the borrow checker. Adding 'static bound, which should make it clear that State cannot borrow, doesn't help.
I remember similar issue but with opaque types: `impl Trait + 'static` is not `'static` if returned from a generic function ยท Issue #76882 ยท rust-lang/rust ยท GitHub.
Edit: I replaced &mut with &, error still holds. I hoped that maybe using interior mutability as a workaround.
Code (playground):
trait View {
type State: 'static;
// initialize the state
fn build_state(&self) -> Self::State;
// `view` uses `self` and `state` to do computations. Return type omitted.
fn render_tree(&self, state: &mut Self::State);
}
impl View for () {
type State = ();
fn build_state(&self) -> Self::State {
()
}
fn render_tree(&self, _state: &mut Self::State) {}
}
fn view_fn<'a>(_: &'a ()) -> impl View + use<'a> {
()
}
fn main() {
let view = view_fn(&());
let mut state = view.build_state();
for _ in 0..10 {
let unit = ();
let view = view_fn(&unit);
view.render_tree(&mut state);
}
}
Error:
1 error[E0597]: `unit` does not live long enough
--> src/main.rs:26:28
|
25 | let unit = ();
| ---- binding `unit` declared here
26 | let view = view_fn(&unit);
| ^^^^^ borrowed value does not live long enough
27 | view.render_tree(&mut state);
28 | }
| - `unit` dropped here while still borrowed
29 | }
| - borrow might be used here, when `view` is dropped and runs the destructor for type `impl View`
|
= note: values in a scope are dropped in the opposite order they are defined
For more information about this error, try `rustc --explain E0597`.
error: could not compile `play` (bin "play") due to 1 previous error
8 posts - 2 participants
๐ท๏ธ Rust_feed