- M31
- Jun 12, 2012
-
|
I've been trying to write some Rust in my free time, and I guess I have to accept that I don't understand anything:
code:struct Container {
cache: std::collections::HashMap<u32, String>,
}
impl Container {
pub fn get(&mut self) -> &str {
let id = 42;
let cache = &mut self.cache;
if let Some(value) = cache.get(&id) {
return value;
}
cache.insert(id, "foo".to_owned());
return cache.get(&id).unwrap();
}
}
this code has the borrow checker yelling at me that I'm making both an immutable and mutable borrow, but I don't understand why. Where am I going wrong? (I found I can use cache.entry().or_insert() which is very nice, but I would like to understand why this method doesn't work)
|
#
¿
Jul 4, 2023 15:37
|
|
- Adbot
-
ADBOT LOVES YOU
|
|
#
¿
May 12, 2024 15:59
|
|
- M31
- Jun 12, 2012
-
|
Thanks everybody! I think I get it now, the first borrow is living longer than I expected due to a borrow checker limitation.
|
#
¿
Jul 5, 2023 15:25
|
|