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 mut
s 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?
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]
}