techmore.in

Rust - Variables

In Rust, variables are a fundamental concept for storing and managing data. Here’s an overview of how variables work in Rust, including syntax, mutability, shadowing, and some best practices.

Basic Syntax

To declare a variable in Rust, you use the let keyword:

rust
fn main() { let x = 5; println!("The value of x is: {}", x); }

Mutability

By default, variables in Rust are immutable, meaning their values cannot be changed after they are set. To make a variable mutable, you use the mut keyword:

rust
fn main() { let mut x = 5; println!("The value of x is: {}", x); x = 6; println!("The value of x is: {}", x); }

Shadowing

Rust allows you to "shadow" a variable by using the same name in the same scope. This allows you to reuse the variable name while potentially changing its type or mutability:

rust
fn main() { let x = 5; println!("The value of x is: {}", x); let x = x + 1; println!("The value of x is: {}", x); let x = "Hello"; println!("The value of x is: {}", x); }

Data Types

Rust is a statically typed language, meaning that the compiler needs to know the types of all variables at compile time. You can specify the type of a variable explicitly:

rust
fn main() { let x: i32 = 5; let y: f64 = 3.14; let z: bool = true; let name: &str = "Alice"; println!("x: {}, y: {}, z: {}, name: {}", x, y, z, name); }

Constants

Constants are similar to immutable variables, but they are declared with the const keyword and must have their type specified. Constants are always immutable and can be declared in any scope, including the global scope:

rust
const MAX_POINTS: u32 = 100_000; fn main() { println!("The maximum points is: {}", MAX_POINTS); }

Example Program

Here’s a complete example demonstrating variable declaration, mutability, shadowing, and constants:

rust
fn main() { // Immutable variable let x = 5; println!("The value of x is: {}", x); // Mutable variable let mut y = 10; println!("The initial value of y is: {}", y); y = 20; println!("The new value of y is: {}", y); // Shadowing let x = x + 1; println!("The value of x after shadowing is: {}", x); let x = "Hello"; println!("The value of x after changing type is: {}", x); // Constant const PI: f64 = 3.14159; println!("The value of PI is: {}", PI); }

Output

When you run the above program, you will get the following output:

csharp
The value of x is: 5 The initial value of y is: 10 The new value of y is: 20 The value of x after shadowing is: 6 The value of x after changing type is: Hello The value of PI is: 3.14159

Summary

  • Immutable Variables: Declared with let, cannot be changed.
  • Mutable Variables: Declared with let mut, can be changed.
  • Shadowing: Reusing a variable name in the same scope.
  • Constants: Declared with const, must have their type specified, and are always immutable.

Understanding these concepts is crucial for working effectively with variables in Rust.