Temporarily pushing borrowed value onto Vec


#1

Is there a way to accomplish the following, or would it require a new with_pushed_value semantic on Vec?

fn foo(x: &T, y: &mut Vec<T>) {
   (*y).push(x); // <-- disallowed because data from "x" flows into "y" here
   // do stuff
   (*y).pop();
}

#2

I think there’s a more fundamental problem here, beyond just the borrow/lifetimes. The Vec is storing owned values, with whatever layout they have, whereas the reference is just a thin pointer.

What type of stuff does // do stuff do? You might be able to abstract over x and the y by, e.g., an iterator over both.


#3

While the value is in the Vec, you’d have mutable access to it, so even if you could fake it some how, that would break the guarantees you got from passing it in immutably.


#4

Ah, yes… If it was a Vec<&T> would that work better?


#5

Sure, that would “just work”.


#6

Yeah, that would work - you’d need to tie the borrow of x with the references inside the Vec but it should work, e.g.:

fn foo<'a, T>(x: &'a T, y: &mut Vec<&'a T>) {
    y.push(x);
    y.pop();
}

#7

BTW, the (*y).foo doesn’t seem to achieve anything over just y.foo.