0

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`.
cafce25
  • 15,907
  • 4
  • 25
  • 31
Abner Matheus
  • 41
  • 1
  • 8
  • 1
    You are likely getting an error because of some specific piece of code. Please update your question to include that error, and the code that produces it. See [mcve]. – user229044 Aug 16 '23 at 13:28
  • 4
    Whether something is copyable doesn't depend on it being on the stack or heap, and rust doesn't copy something just because it's on the stack. – user229044 Aug 16 '23 at 16:48
  • 2
    Rust's ownership rules are independent of where value is stored at. Also rust will not allocate memory on the heap, unless _explicitly_ asked to, and will not clone (in the meaning of `Clone`) values, unless _explicitly_ asked to. – Aleksander Krauze Aug 16 '23 at 16:52
  • Contrary to C/C++, Rust doesn't copy by default. It moves by default, invalidating the old object. It only copies if you mark your struct `#[derive(Clone, Copy)]`. Note that this won't work as soon as you have a more complex member like `String`, as it it can't be trivially copied. Then you will have to `.clone()` explicitly. – Finomnis Aug 16 '23 at 23:21

0 Answers0