3

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.

wizzwizz4
  • 6,140
  • 2
  • 26
  • 62
  • 2
    Note that transmuting an immutable reference to a mutable reference is **always** unsafe, [don't do it ever](https://doc.rust-lang.org/nomicon/transmutes.html). – E_net4 Jun 25 '19 at 21:38

1 Answers1

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].

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
stephaneyfx
  • 306
  • 1
  • 8