After some searching, I haven't found much discussion about the possibility of mutability parameters in Rust. By this, I mean the ability to make a structure/function/implementation generic over whether one of its inputs is mutable or not.
To me, it seems like something which could work similarly to lifetime parameters. The biggest benefit of this kind of genericity would be the avoidance of duplicate getter functions. For example:
impl MyStruct {
fn get_n(&self) -> &i32 {
&self.n
}
fn get_n_mut(&mut self) -> &mut i32 {
&mut self.n
}
}
Could be replaced with (syntax of course up for debate):
impl<mut m> MyStruct<mut m> {
fn get_n(&m self) -> &m i32 {
&m self.n
}
}
With parameters determined by function arguments, like types and lifetimes:
let s_imm = MyStruct::new();
let mut s_mut = MyStruct::new();
let i: &i32 = s_mut.get_n(); // Ok
let i: &i32 = s_imm.get_n(); // Ok
let i: &mut i32 = s_mut.get_n(); // Ok
let i: &mut i32 = s_imm.get_n(); // Compilation error
Has this already been discussed/RFC'd? Is there another way to accomplish this (besides macros)?
The closest I've found is "Abstracting over mutability in Rust", which mentions the use of AsRef
to specify the base type of a parameter, without specifying its reference type (and therefore its mutability). However it looks like this doesn't allow you to retain the mutability of the type, since .as_ref()
will coerce mutable to immutable.