use std::collections::HashMap;
#[derive(Default)]
struct Foo {
map: HashMap<String, String>,
}
fn calc_value() -> String {
"ololo".into()
}
impl Foo {
pub fn get_or_create(&mut self, key: String) -> &str {
self.map.entry(key).or_insert_with(calc_value)
}
pub fn print(&self, value: &str) {
println!("{}", value)
}
}
fn main() {
let mut foo = Foo::default();
let value = foo.get_or_create("key".into());
foo.print(value);
}
error[E0502]: cannot borrow `foo` as immutable because it is also borrowed as mutable
--> src/main.rs:24:5
|
23 | let value = foo.get_or_create("key".into());
| --- mutable borrow occurs here
24 | foo.print(value);
| ^^^ ----- mutable borrow later used here
| |
| immutable borrow occurs here
This code gives error, because I use reference(value
), derived from mutable borrow of self(let value = foo.get_or_create("key".into());
) when I want to get immutable borrow of self (foo.print(value);
). AKAIK it is because lifetime of mutable borrow of self is prolnged until derived reference (returned from get_or_create
) is alive. I don't understand the reason behind that, especially why prolonged borrow is considered mutable, while derived reference is immutable. Is it just limitation of current implementation of borrowchk or there is some unsoundness in doing &mut self -> &self
conversion here unconditionally?