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.
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With