Immutable reference to mutable reference

I believe this is a valid use-case since I don't want to actually mutate the data behind the mutable reference.

I'm using a third-party library that has a trait with functions that take mutable self references, like this:

pub trait Thing {
    fn do(&mut self);
}

My implementation of that trait does not need self to be mutable. I can implement it like this:

impl Thing for MyType {
    fn do(&mut self) {
        let me: &Self = self;
        // Never use `self`. Always use `me`...
    }
}

This is all fine, but for performance reasons I want to call MyType::do using (aliased) immutable references. I know that my implementation doesn't actually need the mutability, but I can't change the third-party trait definition. Is there a way I can call do using an immutable &MyType?

If you know you're calling MyType::do just write another function taking &self. You don't need the trait in that case.

Implement the trait for &MyType (and probably also MyType).

Here's an example of that from std.

6 Likes

Forget about mutability. The proper name for &mut should have been &uniq, because mutability that unique mutable reference grants is a nice side-bonus to uniqueness. Uniqueness is the strict requirement, not mutability.

Rustonomicon gives not one but three answers to this:

That's precisely because on uniqueness requirement is extremely fundamental (mutability is not that important, there are interior mutability, but if you told the compiler that you have unique reference then you have to uphold your promise).

2 Likes