I have two variables of type &T
, x
and y
, which I swap locally inside a function:
pub fn foo<T: Copy>(mut x: &T) {
let y_owned = *x;
let mut y = &y_owned;
for _ in 0..10 {
do_work(x, y);
std::mem::swap(&mut x, &mut y);
}
}
fn do_work<T>(_x: &T, _y: &T) {}
This code fails to compile, giving the following error:
error[E0597]: `y_owned` does not live long enough
--> src/lib.rs:3:22
|
3 | let mut y = &y_owned;
| ^^^^^^^ borrowed value does not live long enough
...
8 | }
| - borrowed value only lives until here
|
note: borrowed value must be valid for the anonymous lifetime #1 defined on the function body at 1:5...
--> src/lib.rs:1:5
|
1 | / pub fn foo<T: Copy>(mut x: &T) {
2 | | let y_owned = *x;
3 | | let mut y = &y_owned;
4 | | for _ in 0..10 {
... |
7 | | }
8 | | }
| |_____^
I fail to see why it shouldn't work. x
and y
have different lifetimes, but why should the compiler require y
to live as long as x
? I am only modifying references locally inside foo
and referenced objects are guaranteed to exist. Once foo
returns, it doesn't matter if these x
and y
even existed, does it?
For larger context, I am implementing mergesort and want to swap the primary and auxiliary (temporary) arrays this way.