4

I did a bit of searching, and found this Reddit post from four years ago, but other than unsafe code:

fn find_mut <'a> (&'a mut self, elem: &T) -> Option<&'a mut Node<T>> {
    unsafe{std::mem::transmute(self.find(elem))}
}   

or a macro, I can't think of any ways to do this.

Alternative restatements of the problem:

  • Make a function generic over mutability.
  • Mutability modifier polymorphism.

Is there a way to do this now?


Motivation, just in case this is another XY problem: I'd like to write a function that processes a vector of references, reading them but not modifying them, and I would like to use those functions both in cases where I will have &Ts and &mut Ts.

1
  • 2
    Note that transmuting an immutable reference to a mutable reference is always unsafe, don't do it ever. Commented Jun 25, 2019 at 21:38

1 Answer 1

1

Based on the motivation you described at the end of your message, my understanding is that you'd like to inspect Vec<&T> and Vec<&mut T> with one function and without modifying the underlying Ts. Does this do what you want? Note that I used references to slices because it's more idiomatic as parameter than references to vectors as the latter coerce to the former.

Playground

use std::ops::Deref;

struct Foo;

fn do_stuff(_: &Foo) {}

fn process<T>(v: &[T])
where
    T: Deref<Target = Foo>,
{
    for x in v.iter().map(|x| x.deref()) {
        do_stuff(x);
    }
}

fn main() {
    process(&[&Foo]);
    process(&[&mut Foo]);
}

Using Borrow instead of Deref, you can also pass &[Foo].

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.