Getter and setters have many use cases, but unfortunately in Rust getters also have this problem where you lose more fine-grained lifetime tracking and get lifetime errors:
pub struct Test {
x: String,
y: String,
}
impl Test {
pub fn get_x_mut(&mut self) -> &mut String {
&mut self.x
}
pub fn get_y_mut(&mut self) -> &mut String {
&mut self.y
}
}
// Works
pub fn test_1(a: &mut Test) {
let x = &mut a.x;
let y = &mut a.y;
x.push('a');
y.push('a');
}
// Doesn't work, lifetime errors
pub fn test_2(a: &mut Test) {
let x = a.get_x_mut();
let y = a.get_y_mut(); // `a` borrowed mut twice
x.push('a');
y.push('a');
}
I'm curious if (1) in principle it's possible to improve this so that test_2
above will work (2) if there are any work planned in rustc that will one day improve this so that test_2
above will work.
Thanks.