Safe `&&T` to `&&mut T` conversion

When you write impl SomeTrait for &mut T, and then use &self in the function signature, you're not referring to &T, because the type Self is not T but &mut T. So &self is actually of type &&mut T (and that's why the original post asked how to convert &&T to &&mut T).

3 Likes

you are trying to "reuse" a wrong abstraction level. the impl<T> Foo for &mut T {} block is not the fundamental unit for reusability, because of the awkwardness of the signature with &&mut T.

whatever that means, but how about a good old free function? which can then be reused both for &mut T and Box<T>:

fn do_foo<T>(this: &mut T, that: &T) {
    todo!("Mutate this based on that")
}

impl<T> Foo for &mut T {
    fn foo(&mut self, other: &Self) {
        do_foo(&mut **self, &**other)
    }
}

impl<T> Foo for Box<T> {
    fn foo(&mut self, other: &Self) {
        do_foo(&mut **self, &**other)
    }
}
4 Likes