Std::mem::replace with two elements of an array

I have an array where I want to use the replace function to replace one element with the another element of that array.
But I can't do:

let mut foo: [u32;2] = [1,2];
replace(&mut foo[0], foo[1]);

because I cannot access an array which I have previously borrowed.
How could I do this instead?

If you are trying to swap the two elements:

foo.swap(0, 1);

If you are merely trying to copy the element at index 1 into the element at index 0 (only possible if the type is Copy):

foo[0] = foo[1];

If you don't have a Copy type, then you can't just move out of any element of an array without providing a replacement. Perhaps what you really have is a Vec, in which case you could do:

let mut foo = vec![1, 2];
foo.swap_remove(0);

or

let mut last = foo.pop().expect("empty vector");
foo[0] = last;
5 Likes

If you really need two mutable references simultaneously, you can get them with either pattern matching or split_at_mut():

// requires exactly length 2 (or whatever you write in the pattern)
let [foo_0, foo_1] = &mut foo;
mem::replace(foo_0, *foo_1);

// uses indexing
let (first, second) = foo.split_at_mut(1);
mem::replace(&mut first[0], second[0]);
2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.