Look like keyword 'let' for mutable variable is unnecessary


#1

Hello all,
For mutable variable binding, we don’t need ‘let’, just ‘mut’ is enough:

mut x = 5

Looks like the syntax is clearer.
So why is let used here?


#2

Thanks for asking, and welcome! This is a FAQ.


#3

What version of the Rust compiler are you using?

When running your code with cargo build --verbose or cargo run --verbose whilst using rustc 1.0.0-nightly (i.e. rustc --version) and cargo 0.0.1-pre-nightly (i.e. cargo --version) gives the following errors:

error: expected identifier, found keyword `mut`
error: expected one of `!`, `.`, `::`, `;`, `{`, `}`, or an operator, found `x`

let doesn’t appear to have been used in your code snippet, but if you were to change it and prefix the expression on the left hand side with a let, and then add a semi-colon to the end of your the expression on the right hand side so that the right hand side expression becomes a statement instead, then it would become a declaration and it would bind the value on the right hand side of the assignment operator to the variable expression on the left hand side. Rust bindings are immutable by default. Mutable bindings may be used with an additional mut prefix between the let and the expression on the left hand side of the assignment operator. Rust’s type inference automatically determines the type of an expression. To achieve type safety you may explicitly supply a type with a colon after the variable expression, such as:

// below the `let` declares a mutable binding between a statement having a value of 5 and variable expression x, where the variable expression x has been explicitly declared to only allow values to be bound to it that are signed 32-bit integer type
let mut x: i32 = 5; 

#4

Mutability is attached to identifier binding patterns, not to let. That is, let mut x is not a “let mut” construct, it is let used with a mut x pattern. Binding a mutable variable works anywhere a pattern can be, e.g. let (mut x, y) = some_tuple; or fn foo(mut z: i32) or match an_option { Some(mut w) => .... See also a recent reddit thread.

@ltfschoen (I think @foor knows that the mut x = 5; form doesn’t work, and is asking why.)


#5

Thanks @huon, now I am clear why we need let here :smile: