struct Foo {
data: Option<u8>,
}
impl Foo {
fn get(&mut self) -> &u8 {
if let Some(data) = self.data.as_ref() {
if *data > 10 {
return data;
}
}
self.data.insert(20)
}
}
Compiling playground v0.0.1 (/playground)
error[E0502]: cannot borrow `self.data` as mutable because it is also borrowed as immutable
--> src/main.rs:13:9
|
6 | fn get(&mut self) -> &u8 {
| - let's call the lifetime of this reference `'1`
7 | if let Some(data) = self.data.as_ref() {
| ------------------ immutable borrow occurs here
8 | if *data > 10 {
9 | return &data;
| ----- returning this value requires that `self.data` is borrowed for `'1`
...
13 | self.data.insert(20)
| ^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
For more information about this error, try `rustc --explain E0502`.
error: could not compile `playground` (bin "playground") due to previous error
I expect that this should compile because when the code flow exits the if statements, data is dropped and so is the immutable borrow on self.data.
A browser interface to the Rust compiler to experiment with the language