Reputation: 48058
Is it possible in Rust to swap 2 vectors (without shadowing previous variables), by making them point to each-others in-memory representation?
I'm porting some code from C, which is quite straightforward when dealing with pointers.
Pseudo-code (C-like):
float *a = malloc(size);
float *b = malloc(size);
error = calc_params(curve, a);
for (i = 0; i < REFINE_ITER_MAX; i++) {
/* reads 'a', refines to 'b' */
calc_params_refine(curve, a, b);
error_test = calc_params(curve, a);
if (error_test < error) {
/* How to do this in Rust??? */
float *swap = a;
a = b;
b = swap;
}
else {
break;
}
}
The code above refines one array into another, using source/destination arrays which are swapped each step.
Given two vectors which are the same length and use primitive types (float
/i32
/usize
... etc), how would this be done in Rust?
From reading mem::swap()
documentation, its not clear to me how this applies to Vec
types: "Swap the values at two mutable locations of the same type, without deinitializing or copying either one."
For all I know, the vectors could be resized in-place and data copied between them - while still fitting the description given.
Upvotes: 3
Views: 3470
Reputation: 88696
The function std::mem::swap
is doing exactly what you want. Take this example:
let mut a = vec![/* fill this vector */];
let mut b = Vec::new();
loop {
// do something ...
std::mem::swap(&mut a, &mut b);
}
swap
doesn't touch the vectors' contents at all. It just swaps the raw bytes on the stack (this includes the pointer to the data as well as the length and capacity field). It really is "swapping names".
Upvotes: 11
Reputation: 299900
Rust has a std::mem
module containing a number of functions for such use cases.
In this case you are interested in std::mem::swap
, which exchanges the content of two given objects.
Upvotes: 1