Variables
⚠️Be Sure to learn about the ownership in Rust before reading this article.
Consider the following example around variable assignment in JavaScript:
let x = 5;
And the same in Rust:
let x: i32 = 5;
Rust is type-safe: the compiler guarantees that the value stored in a variable is always of the designated type. The example can be simplified by using the compiler's ability to automatically infer the types of the variable. In JavaScript:
let x = 5;
In Rust:
let x = 5;
When expanding the first example to update the value of the variable (reassignment), the behavior of JavaScript and Rust differ:
let x = 5;
x = 6;
console.log(x); // 6
In Rust, the identical statement will not compile:
let x = 5;
x = 6; // Error: cannot assign twice to immutable variable 'x'.
println!("{}", x);
In Rust, variables are immutable by default. Once a value is bound to a name, the variable's value cannot be changed. Variables can be made mutable by adding mut
in front of the variable name:
let mut x = 5;
x = 6;
println!("{}", x); // 6
Rust offers an alternative to fix the example above that does not require mutability through variable shadowing:
let x = 5;
let x = 6;
println!("{}", x); // 6
JavaScript also supports shadowing, e.g. locals can shadow fields and type members can shadow members from the base type. In Rust, the above example demonstrates that shadowing also allows to change the type of a variable without changing the name, which is useful if one wants to transform the data into different types and shapes without having to come up with a distinct name each time.
See also:
- Data races and race conditions for more information around the implications of mutability
- Scope and shadowing
- Memory management for explanations around moving and ownership