I'm pretty new to Rust, and I'm trying to understanding the core concept of it which is ownership and borrowing. I already read the book and some other articles, but it still confuses me.
I have a struct defined like this:
#[repr(C)]
#[derive(Copy, Clone)]
pub struct Element(pub (crate) [u64; 12]);
I have an external function which swaps the values of two Element
based on the flag
value. If flag
is 0, they are not swapped, and if flag
is 1, they are swapped. That's why in the prototype I use &mut
:
extern {
pub fn swap(x: &mut Element, y: &mut Element, flag: u8);
}
I create a wrapper method in Rust around this external function:
impl for Element {
fn wrapper_swap(&mut self, y: &mut Element, flag: u8) {
unsafe {
swap(self, y, flag); // OR swap(&mut self, &mut y, flag); ?!
}
}
}
My wrapper_swap
function has the same signature as the external prototype function swap
. How do I need to call the external function swap
here?
Since self
and y
already are defined as &mut self
and &mut y
, can I just call the swap function as swap(self, y, flag);
? Or will that remove the mutable references, and actually I need to call it as swap(&mut self, &mut y, flag);
?
It also gets complicated for me as to how I call it with actual values. For example, I have three variables defined like this:
let mut one = Element([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]);
let mut two = Element([2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]);
let flag: u8 = 0;
Since the variables are already defined as mutable, do I need to call the wrapper_swap
function as (&one).wrapper_swap(&two, flag);
or will this make references immutable no matter that the variables are defined as mutable, and instead I need to call it as (&mut one).wrapper_swap(&mut two, flag);
? Which is the correct approach?
Maybe it's because I'm using unsafe functions, but the compiler does not complain about how I call this function.
What would happen if the variables one
and two
were not defined as mutable? Can I still borrow them mutable as &mut one
or &mut two
, and change their value in another function?