Task
A simple data-structure that gets and sets a value of a field in a struct
.
Issue
The following get_or_set
function errors with
cannot borrow
*self
as mutable because it is also borrowed as immutable
Code
struct MyValue<A> {
value: Option<A>,
}
impl<A> MyValue<A> {
fn get(&self) -> &Option<A> {
&self.value
}
fn set<F: FnOnce() -> A>(&mut self, setter: F) -> &Option<A> {
self.value = Some(setter());
self.get()
}
//this function is causing borrow error
fn get_or_set<F: FnOnce() -> A>(&mut self, setter: F) -> &Option<A> {
match self.get() {
None => self.set(setter),
some @ Some(_) => some
}
}
}
Why does the error occur?
Following the error the issue is that I am call self.set
a second time before the first self.get
goes out of scope and multiple borrows are not allowed.
Fix:
Use if
& else
instead. Here I'm calling self.get
twice which is not nice.
fn get_or_set<F: FnOnce() -> A>(&mut self, setter: F) -> &Option<A> {
if self.get().is_some() {
self.get()
} else {
self.set(setter)
}
}
Question
How do I get the borrow check to allow the match statement to pass as well? My attempt at setting lifetimes has not succeeded.
fn get_or_set<'a, F: FnOnce() -> A + 'a>(&'a mut self, setter: F) -> &'a Option<A>