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, foo);
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:
If you are merely trying to copy the element at index 1 into the element at index 0 (only possible if the type is
foo = foo;
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];
let mut last = foo.pop().expect("empty vector");
foo = last;
If you really need two mutable references simultaneously, you can get them with either pattern matching or
// requires exactly length 2 (or whatever you write in the pattern)
let [foo_0, foo_1] = &mut foo;
// uses indexing
let (first, second) = foo.split_at_mut(1);
mem::replace(&mut first, second);
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.