I don't know if I understand correctly but fixed size variables are allocated on the stack and dynamic size variables are allocated on the heap correct?
If yes, why when I create a struct and store it in a variable after I say that another variable receives this one, does it give me a borrow error? shouldn't he just clone the value as with an i32, u32, f32 etc?
Shouldn't this error only happen with strings, vec, box etc etc ?
If not, what did I still not understand?
This works:
fn main() {
let x: i32 = 5;
let y: i32 = x;
println!("x : {}", x);
println!("y : {}", y);
}
This does not work:
struct User {
pub name: String,
pub age: u8,
}
fn main() {
let u1 = User { name: "John".to_string(), age: 20 };
let u2 = u1;
println!("U1 Name: {} \n", u1.name);
println!("U1 Age: {} \n", u1.age);
}
Error:
error[E0382]: borrow of moved value: `u1`
--> src/main.rs:13:29
|
8 | let u1 = User { name: "John".to_string(), age: 20 };
| -- move occurs because `u1` has type `User`, which does not implement the `Copy` trait
9 | let u2 = u1;
| -- value moved here
...
13 | println!("U1 Age: {} \n", u1.age);
| ^^^^^^ value borrowed here after move
|
= note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)
For more information about this error, try `rustc --explain E0382`.