I'm trying to understand why this doesn't compile and how to overcome the problem. This is a more or less distilled version of my actual code. Here i'm having an Elem
that holds a reference to an item in Container
. The container is stored in Root
and is manipulated by it. Elem
can't ever outlive the container, but I can't seem to prove that to the compiler.
The immediate issue is that I can't run the set
function twice.
I have tried to remove the constraint in the set
function, but then the compiler returns an error, that self
doesn't live as long as its type, which doesn't make much sense to me.
Thanx.
struct Elem<'a> {
num: &'a u32
}
impl<'a> Elem<'a> {
fn new(num: &'a u32) -> Self {
Self { num }
}
}
struct Container<'a> {
num: u32,
elem: Option<Elem<'a>>
}
impl<'a> Container<'a> {
fn new() -> Self {
Self {
num: 0,
elem: None,
}
}
fn set(&'a mut self, num: u32) {
self.num = num;
self.elem = Some(Elem::new(&self.num));
}
}
struct Root<'a> {
cnt: Container<'a>
}
impl<'a> Root<'a> {
fn new () -> Self {
Self { cnt: Container::new() }
}
fn set(&'a mut self, num: u32) {
self.cnt.set(num);
self.cnt.set(num);
}
}
fn main() {
}
Errors:
Compiling playground v0.0.1 (/playground)
error[E0499]: cannot borrow `self.cnt` as mutable more than once at a time
--> src/lib.rs:42:9
|
35 | impl<'a> Root<'a> {
| -- lifetime `'a` defined here
...
41 | self.cnt.set(num);
| -----------------
| |
| first mutable borrow occurs here
| argument requires that `self.cnt` is borrowed for `'a`
42 | self.cnt.set(num);
| ^^^^^^^^^^^^^^^^^ second mutable borrow occurs here
For more information about this error, try `rustc --explain E0499`.
error: could not compile `playground` due to previous error