This error occurs because a value was dropped while it was still borrowed.
This note is still a seedling.
I keep these in the open and tend them as I learn, so this page grows over time rather than arriving finished. Expect rough edges.
:: ON THIS PAGE 3
Error Message
error[E0597]: `request_data` does not live long enough
--> src/main.rs:28:22
|
23 | let request_data = String::from("User Request (Short Lived)");
| ------------ binding `request_data` declared here
...
28 | request: &request_data,
| ^^^^^^^^^^^^^ borrowed value does not live long enough
...
34 | } // <--- 'request_data' dies here. 'ctx' dies here.
| - `request_data` dropped here while still borrowed
...
37 | println!("I am still alive: {}", saved_request_ref);
| ----------------- borrow later used here
Code
structContext<'a, 'b>{config:&'astr,
request:&'bstr,
}impl<'a, 'b>Context<'a, 'b>{fnget_config(&self)->&'astr{self.config
}fnget_request(&self)->&'bstr{self.request
}}fnmain(){let config_data =String::from("Global Config (Long Lived)");let saved_config_ref;let saved_request_ref;{// Issue is here! request_data dies inside this scope!
let request_data =String::from("User Request (Short Lived)");// Creates the context holding both
let ctx = Context { config:&config_data, request:&request_data,};// We extract the config reference
saved_config_ref = ctx.get_config(); saved_request_ref = ctx.get_request();}// <--- 'request_data' dies here. 'ctx' dies here.
println!("I am still alive: {}", saved_config_ref);println!("I am still alive: {}", saved_request_ref);}
Fix
fnmain(){let config_data =String::from("Global Config (Long Lived)");let saved_config_ref;let saved_request_ref;// moved here to maintain lifetime scope
let request_data =String::from("User Request (Short Lived)");{// Creates the context holding both
let ctx = Context { config:&config_data, request:&request_data,};// We extract the config reference
saved_config_ref = ctx.get_config(); saved_request_ref = ctx.get_request();}// <--- 'request_data' dies here. 'ctx' dies here.
println!("I am still alive: {}", saved_config_ref);println!("I am still alive: {}", saved_request_ref);}