In the following rust example, a Values
structure holds a list of values and a Refs
structure holds some references to those values. This code yields a compiler error, shown at the bottom of the post, indicating that in generate_ref
self.values
essentially must have a lifetime of 'a
, making it impossible to generate ref2
even though the reference used to generate ref1
is in its own code block.
pub struct Values {
values: Vec<i32>,
}
impl<'a> Values {
pub fn new() -> Values {
Values { values: vec![] }
}
pub fn generate_ref(&mut self) -> &'a mut i32 {
self.values.push(1);
self.values.last_mut().unwrap()
}
}
pub struct Refs<'a> {
ref1: &'a mut i32,
ref2: &'a mut i32,
}
impl<'a> Refs<'a> {
pub fn new(values: &'a mut Values) -> Refs {
let ref1 = { values.generate_ref() };
let ref2 = { values.generate_ref() };
Refs { ref1, ref2 }
}
}
fn main() {
let mut values = Values::new();
let refs = Refs::new(&mut values);
let ref3 = { values.generate_ref() };
}
error[E0495]: cannot infer an appropriate lifetime for lifetime parameter in function call due to conflicting requirements
--> src\main.rs:12:9
|
12 | self.values.last_mut().unwrap()
| ^^^^^^^^^^^
|
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 10:5...
--> src\main.rs:10:5
|
10 | / pub fn generate_ref(&mut self) -> &'a mut i32 {
11 | | self.values.push(1);
12 | | self.values.last_mut().unwrap()
13 | | }
| |_____^
note: ...so that reference does not outlive borrowed content
--> src\main.rs:12:9
|
12 | self.values.last_mut().unwrap()
| ^^^^^^^^^^^
note: but, the lifetime must be valid for the lifetime `'a` as defined on the impl at 5:6...
--> src\main.rs:5:6
|
5 | impl<'a> Values {
| ^^
note: ...so that reference does not outlive borrowed content
--> src\main.rs:12:9
|
12 | self.values.last_mut().unwrap()
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
What I really need is to ensure that the reference returned from generate_ref
lasts as long as the value stored in Values
. How can I do that? If that is not possible, is there a different way to structure this code that is valid in Rust?
Edit
For more context, this is a simplified example. In the actual implementation, Values
holds onto a bus::Bus
to broadcast data to the receivers. The receivers are produced by the Bus
. Various other structs contain receivers (bus::BusReader
) and references to the broadcaster (&mut bus::Bus
), but only one broadcaster exists for each channel.