tl;dr blocked by "argument requires that `x` is borrowed for `'y`"; how can I coerce variable x
to lifetime 'y
?
Given the following code, I'm blocked when trying to create the Box
pointer pointing to a reference. I know the referenced object instance lives long enough. However, the rust compiler is concerned it does not.
How do I tell the rust compiler that Box::new(&thing)
is valid for the lifetime of the containing struct instance?
Code example
This code is essentially:
Things
(aVec
), holding multipleThing
s- counter of
Thing
s (aHashMap
), holding multipleBox
pointers to different&Thing
as keys, au64
count as values
(My best attempt at) a minimal example (rust playground):
use std::collections::HashMap;
type Thing<'a> = (&'a str, usize);
type Things<'a> = Vec<Thing<'a>>;
type ThingsCounterKey<'a> = Box<&'a Thing<'a>>;
type ThingsCounter<'a> = HashMap<ThingsCounterKey<'a>, u64>;
pub struct Struct1<'struct1> {
things1: Things<'struct1>,
thingscounter1: ThingsCounter<'struct1>,
}
impl<'struct1> Struct1<'struct1> {
pub fn new() -> Struct1<'struct1> {
Struct1{
things1: Things::new(),
thingscounter1: ThingsCounter::new(),
}
}
fn things_update(&mut self, thing_: Thing<'struct1>) {
self.things1.push(thing_);
let counter = self.thingscounter1.entry(
ThingsCounterKey::new(&thing_)
).or_insert(0);
*counter += 1;
}
}
fn main() {
let mut s1 = Struct1::new();
for (x, y) in [("a", 1 as usize), ("b", 2 as usize)] {
s1.things_update((x, y));
}
}
This results in compiler error:
error[E0597]: `thing_` does not live long enough
--> src/main.rs:24:35
|
14 | impl<'struct1> Struct1<'struct1> {
| -------- lifetime `'struct1` defined here
...
24 | ThingsCounterKey::new(&thing_)
| ----------------------^^^^^^^-
| | |
| | borrowed value does not live long enough
| argument requires that `thing_` is borrowed for `'struct1`
...
27 | }
| - `thing_` dropped here while still borrowed
For more information about this error, try `rustc --explain E0597`.
error: could not compile `playground` due to previous error
How can I tell the rust compiler "&thing_
has the lifetime of 'struct1
"?
Similar questions
Before this Question is marked as duplicate, these questions are similar but not quite the same. These Questions address 'static
lifetimes or other slightly different scenarios.
- Argument requires that value is borrowed for
'static
not working for non copy value - Argument requires that _ is borrowed for 'static - how do I work round this?
- "argument requires that
record
is borrowed for'static
" when using belonging_to associations with tokio-diesel - (tokio::spawn) borrowed value does not live long enough -- argument requires that
sleepy
is borrowed for'static
- Rust lifetime syntax when borrowing variables
- Borrow data out of a mutex "borrowed value does not live long enough"
- Rust: argument requires that borrow lasts for
'static