Understanding Variable Bindings in Rust

Understanding Variable Bindings in Rust

This document from Rust By Example delves into the essential concept of variable declarations in Rust, which is fundamental for beginners learning this powerful programming language.

Key Concepts

  • Variable Declaration: In Rust, you can declare a variable using the let keyword, which allows you to create a variable that can hold a value.
  • Immutable by Default: Variables in Rust are immutable by default. Once a value is assigned to a variable, it cannot be changed unless specified otherwise.
  • Mutable Variables: To declare a variable as mutable (changeable), you must use the mut keyword.
  • Shadowing: Rust permits shadowing, allowing you to declare a new variable with the same name as a previous variable, effectively hiding the old one.

Examples

Basic Variable Declaration

let x = 5;
  • In this example, x is declared with a value of 5 and cannot be changed.

Mutable Variable Declaration

let mut y = 10;
y = 15; // This is allowed because y is mutable
  • Here, y is mutable, allowing its value to be reassigned.

Shadowing

let z = 3;
let z = z + 1; // This creates a new z that shadows the old one
  • This second declaration of z creates a new variable that shadows the previous one, resulting in z now being 4.

Conclusion

Understanding variable bindings in Rust is crucial for managing data within your programs. Remember the differences between immutable and mutable variables, as well as how shadowing works, to effectively utilize variables in your Rust code.