I wanted to build a function/method that could adapt if a non-mutable or mutable reference was provided.
I tried something like this (playground):
trait TryAsMut<'a, T> where T: 'a {
fn try_as_mut(self) -> Result<&'a mut T,&'a T>;
}
impl<'a, T> TryAsMut<'a, T> for &'a T {
fn try_as_mut(self) -> Result<&'a mut T,&'a T> {Err(self)}
}
impl<'a, T> TryAsMut<'a, T> for &'a mut T {
fn try_as_mut(self) -> Result<&'a mut T,&'a T> {Ok(self)}
}
fn option_inc<'a>(value: impl TryAsMut<'a, usize>) -> Option<usize> {
match value.try_as_mut() {
Ok(u) => { *u += 1; None },
Err(u) => { Some(*u + 1) },
}
}
fn main() {
let mut u = 5;
println!("u + 1 = {}", option_inc(&u).unwrap());
option_inc(&mut u);
println!("u = {u}");
}
resulting in:
Compiling playground v0.0.1 (/playground)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.58s
Running `target/debug/playground`
Standard Output
u + 1 = 6
u = 6
It works, but is there an idiomatic way of doing it?
3