In Rust, values are often "moved" around in the memory. For instance, in the following program:
fn sayHello(name: String) {
println!("{}", name);
}
fn main() {
let name = "Clément".to_string();
sayHello(name);
}
The name
variable is moved when used by sayHello
.
My question is: why do the variable needs to be moved in the memory? Why can't it stay to its initial location, and the compiler just turn it under the hood into something like:
fn sayHello(name: &String) {
println!("{}", name);
}
fn main() {
let name = "Clément".to_string();
sayHello(&name);
}
This would avoid to have to move the data, which implies a 1:1 copy, which means we have to perform (not always but often) an allocation to copy the data, and then write it to the memory, which is very costly.
I didn't find any resource on this, and I though about "moving" maybe not being about "moving the values in the memory" but many articles seems to tell the opposite.
Could anyone help me understand this ?
EDIT: Ok so by moving I indeed meant memcpy()
and instead of String
which has some pointed out is essentially made of a pointer + length, let's say an [u8; 16]
or anything that does not contain a pointer itself.