Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
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)

Adbot
ADBOT LOVES YOU

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.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply