Argument requires that `'x` must outlive `'a`
⚓ Rust 📅 2026-03-07 👤 surdeus 👁️ 1Hi !
I'm entering in the lifetime world. Until today I had avoided them. But, I have to face them in generic rewrite of my code.
There is a reproduction of my problem:
use std::sync::{Arc, RwLock};
struct SoldierId(usize);
struct Soldier;
struct World(Vec<Soldier>);
struct State(Arc<RwLock<World>>);
struct Context {
state: Arc<State>,
}
trait IntoSubject<'a, T> {
fn into_subject(&self, world: &'a World) -> &'a T;
}
impl<'a> IntoSubject<'a, Soldier> for SoldierId {
fn into_subject(&self, world: &'a World) -> &'a Soldier {
&world.0[self.0]
}
}
struct Processor<'a> {
ctx: &'a Context,
}
impl<'a> Processor<'a> {
fn process<I, T: 'a>(&self, i: I)
where
I: IntoSubject<'a, T>,
{
let world = self.ctx.state.0.read().unwrap();
let _subject = i.into_subject(&world);
}
}
fn main() {
let objects = vec![];
let state = Arc::new(State(Arc::new(RwLock::new(World(objects)))));
let ctx = Context { state };
let processor = Processor { ctx: &ctx };
processor.process(SoldierId(0));
}
error[E0597]: `world` does not live long enough
--> src/main.rs:31:39
|
25 | impl<'a> Processor<'a> {
| -- lifetime `'a` defined here
...
30 | let world = self.ctx.state.0.read().unwrap();
| ----- binding `world` declared here
31 | let _subject = i.into_subject(&world);
| ---------------^^^^^^-
| | |
| | borrowed value does not live long enough
| argument requires that `world` is borrowed for `'a`
32 | }
| - `world` dropped here while still borrowed
In this context, my subject (T) is owned by World. So, in Process::process which contain World (thought State then Context), the life of T must be the same as World. So, I specfy 'a. Error say &world is dropped (l. 32) but still borrowed. How to indicate than T no need to be dropped after world ? Maybe I'm talking nonsense ![]()
Thanks in advance !
2 posts - 2 participants
🏷️ Rust_feed