1

I have the following snippet of Rust:

pub fn scope(&mut self) -> &mut HashMap<String, Type> {
    let idx = self.vars.len() - 1;
    &mut self.vars[idx]
}

I've realized that I have some contexts where I would like to use this function with a non-mutable version of the function e.g.:

pub fn scope(&self) -> &HashMap<String, Type> {
    let idx = self.vars.len() - 1;
    &self.vars[idx]
}

There's only 3 muts removed between the two functions. Can I somehow turn these into one function that derives the mutability of my returned reference depending on the mutability of self? Is there perhaps some kind of trait I can make use of or similar?

Shepmaster
  • 326,504
  • 69
  • 892
  • 1,159
lfxgroove
  • 3,608
  • 2
  • 22
  • 32

1 Answers1

6

You cannot have a single function to achieve that. However, it is actually conventional (and recommended by the API guidelines) to have _mut variants of the same function for that purpose:

pub fn scope(&self) -> &HashMap<String, Type> {
    let idx = self.vars.len() - 1;
    &self.vars[idx]
}

pub fn scope_mut(&mut self) -> &mut HashMap<String, Type> {
    let idx = self.vars.len() - 1;
    &mut self.vars[idx]
}
E_net4 - Krabbe mit Hüten
  • 24,143
  • 12
  • 85
  • 121