Temporarily pushing borrowed value onto Vec

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();
}
1 Like

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.

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.

1 Like

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

Sure, that would “just work”.

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();
}
1 Like

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

1 Like