I'm trying to get something like
use std::collections::HashSet;
#[derive(PartialEq, Eq, Hash, Clone, Copy)]
struct Ref<'a>(&'a ());
fn get_ref<'a>(v: (), set: &HashSet<Ref<'a>>) -> Option<Ref<'a>> {
set.get(&Ref(&v)).copied()
}
to work (imagine there was something actually useful in the hashset instead of ()). This does not compile:
error[E0515]: cannot return value referencing function parameter `v`
--> <source>:7:5
|
7 | set.get(&Ref(&v)).copied()
| ^^^^^^^^^^^^^--^^^^^^^^^^^
| | |
| | `v` is borrowed here
| returns a value referencing data owned by the current function
If I'm not mistaken, lifetime inference should require that the value returned by get have the same lifetime as set, but the value passed into get should be able to have any lifetime as long as it exists for the duration of that call, as get doesn't actually put it anywhere. However, this seems not to be the case, and I don't understand why this limitation exists.
Is there a way to get around this using safe code? I could just unsafe{ transmute(&v) } or equivalent but I would prefer not to if there is a better way.