Jargon #0 - Mutability
Course: Rust Bootcamp - chapter 11
Mutability
Section titled “Mutability”Immutable variables represent variables whose value cant be changed once assigned
fn main() { let x: i32 = 1; x = 2; // Error because x is immutable println!("{}", x);}By default, all variables in Rust are immutable because
- Immutable data is inherently thread-safe because if no thread can alter the data, then no synchronization is needed when data is accessed concurrently.
- Knowing that certain data will not change allows the compiler to optimize code better.
You can make variables mutable by using the
mutkeyword
fn main() { let mut x: i32 = 1; x = 2; // No error println!("{}", x);}💡 const in Javascript is not the same as immutable variables in rust. In JS, you can still update the contents of const
arraysandobjects
💡 JS also has a concept of immutability that a lot of libraries were built on in the past - https://www.npmjs.com/package/immutable