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
Sweeper
Nov 29, 2007
The Joe Buck of Posting
Dinosaur Gum
I'm basically know nothing about rust, but is there any way to "hide" mutability of a struct?

code:
use std::collections::HashMap;

struct Test<'a> {
    map: HashMap<&'a str, u32>
}

impl<'a> Test<'a> {
    fn new() -> Test<'a> {
        return Test {
            map: HashMap::new()
        }
    }

    fn size(&self) -> usize {
        return self.map.keys().count();
    }

    fn add(&self, key: &'a str, count: u32) {  <------ I don't want to have to pass &mut self
        self.map.insert(key, count);
    }

}

fn main() {
    let t = Test::new();

    t.add("test", 1);
    println!("{}", t.size());
}
How do I not pass '&mut self' to the add function, and keep it as &self? I don't want to declare every object as mutable because a map it contains is mutable. I'd like to hide that implementation detail from the consumer...

Also is there any long winded explanation of lifetimes, I'm an idiot and need more words

Adbot
ADBOT LOVES YOU

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