My use case is a bit more complex than this, but I'm trying to simplify the issue with this abstract example.
Say I have a structure:
struct Foo {
bar: u32,
baz: u32,
....
}
Run Code Online (Sandbox Code Playgroud)
How can I write a get_bar function which can generalize over the mutability of the self parameter?
Pseudocode:
struct Foo {
bar: u32,
baz: u32,
....
}
Run Code Online (Sandbox Code Playgroud)
If called with a mutable pointer, it would return a mutble pointer to the inner field, if called with an immutable, it would return an immutable.
My goal is to avoid having to define a nonmut and a mut version of each function, by copy pasting code basically:
impl Foo {
fn get_bar(&self) -> &u32 { &self.bar }
fn get_bar_mut(&mut self) -> &mut u32 { &mut self.bar }
}
Run Code Online (Sandbox Code Playgroud)
If the body of the function is more complex than this (my case is a recursive function), it gets pretty nasty, and there is a lot of code that is being copy&pasted, something that should be avoided.