(rust book) confusion on seemingly paradox compiler errors

Hello,

I am toying around a bit and when I want to compile

fn main() {
    let mut var = 5;
    let x = var;
    x = x+1;
    println!("{}", var);

the compiler says I should consider adding "mut" to x. When I have written "let mut x = var;" I get
a warning " warning**: variable does not need to be mutable**". I wanted to see if ownership is transferred from "var" to "mut" can someone explain to me whats going on? Thanks!

The compiler's messages are correct. Whether an owned value is mutable is not determined by its first owner but its current owner.

  • var does not need to be a mutable variable because it is never assigned or otherwise mutated.
  • x needs to be a mutable variable because you assign to it.

I wanted to see if ownership is transferred from "var" to "mut" can someone explain to me whats going on?

Ownership of a copy of 5 is transferred to x. That copy is completely independent of what's in var. (Notice that the program will print 5, not 6.) If you want to modify var through x, you need to take a reference to var:

    let mut var = 5;
    let x = &mut var;
    *x = *x + 1;
    println!("{}", var);

This program will print 6 and have no warnings about mutability.

It may be easier to understand ownership and mutability if you write your experimental programs with values which aren't copiable, like String or Vec<i32>. Built-in number types all implement Copy, which means that you can transfer ownership and then still use the value in the original place, because there's no reason to make it invalid and it's a lot easier to do arithmetic that way. But if you wrote a program with a String:

    let var = String::from("hello");
    let mut x = var;
    x.push_str(" world");
    println!("{}", var);

then you'd get a "borrow of moved value" error, because the String originally placed in var has been moved to x and no longer exists in var — var contains no value; it has been “moved out of” or “deinitialized”.

5 Likes

thanks for your elaborate answer! :slight_smile:

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.