Hello, I'm new here, please be nice
Suppose I have this struct, with these implemented functions:
use std::collections::BTreeMap;
use std::fmt::Debug as DebugTrait;
pub struct Font;
pub struct DebugRenderer<'a> {
pub font: &'a Font; // not important for this example, must live for the lifetime of this struct
}
impl DebugRenderer<'_> {
// a canvas is passed here, but I will use println! instead to demonstrate
fn draw_to_canvas(&self, values: &BTreeMap<&'static str, &dyn DebugTrait>) {
for item in values.iter() {
println!("{0}: {1:?}", item.0, item.1);
}
}
}
However, with this main function, it doesn't compile: Playground
fn main() {
let mut values: BTreeMap<&'static str, &dyn DebugTrait> = BTreeMap::new();
let font = Font;
let debug_renderer = DebugRenderer { font: &font };
for i in 1..=5 {
values.insert("example value", &i);
debug_renderer.draw_to_canvas(&values);
values.clear();
println!("hey {i}");
}
}
(creating a BTreeMap outside of a loop, passing in a reference in the loop, clearing the map [and therefore its stored references] before the next iteration [which should resolve lifetime issues?])
Here's the error:
Compiling playground v0.0.1 (/playground)
error[E0597]: `i` does not live long enough
--> src/main.rs:22:40
|
21 | for i in 1..=5 {
| - binding `i` declared here
22 | values.insert("example value", &i);
| ------ borrow later used here ^^ borrowed value does not live long enough
...
26 | }
| - `i` dropped here while still borrowed
For more information about this error, try `rustc --explain E0597`.
but i
is dropped after the reference has been removed from the BTreeMap.
I know this can be fixed with creating a new BTreeMap for each iteration of the loop, and passing ownership, but I'd like to simply reuse an existing one in order to save performance costs. I may be misguided, please bear with me if I'm approaching this problem incorrectly, thanks!