Rust Variables and Mutability Explained
Tags: rust, tutorial, beginners, programming
Published: 2024-03-12 05:52:18

Rust is a modern, systems programming language known for its performance, safety features, and expressive syntax. One of the key concepts in Rust is how it handles variables and mutability. In this article, we'll explore how variables are declared and managed in Rust, including mutability, shadowing, and constants.

## Variables in Rust

In Rust, variables are declared using the `let` keyword. By default, variables are immutable, meaning their values cannot be changed once assigned. Here's an example:

```rust
let x = 5; // immutable variable
```

To create a mutable variable, you can use the `mut` keyword:

```rust
let mut y = 10; // mutable variable
y = 15; // valid because y is mutable
```

## Type Annotations

While Rust can often infer the variable type, you can explicitly specify it using a type annotation. This can be useful for clarifying the type of a variable, especially in complex situations. Here's an example:

```rust
let message: &str = "Hello, Rust!"; // type annotation for a string reference
```

## Shadowing

Rust allows shadowing, where you can redeclare a variable with the same name, effectively creating a new variable that hides the previous one. This can be useful for changing the value or type of a variable while keeping the same name. Here's an example:

```rust
let z = "20"; // &str type
// shadows the previous z
let z: i32 = z.parse().unwrap(); // number type
```

## Constants in Rust

Constants in Rust are declared using the `const` keyword. Constants must have a specified type, and their values cannot be changed. They are also immutable by default and cannot be declared as mutable. Here's an example of a constant:

```rust
const PI: f64 = 3.14;
```

## Example Combining Mutability, Shadowing, and Constants

```rust
const MAX_POINTS: u32 = 100_000; // same as 100000

fn main() {
    let mut counter = 0; // mutable variable
    counter += 1;

    let counter = counter * 2; // shadows the previous counter, new variable with different type
    // counter += 1; // Uncommenting this line would result in a compilation error, as counter is no longer mutable

    println!("Max Points: {}", MAX_POINTS);
    println!("Counter: {}", counter);
}
```

In this example, we've used mutability, shadowing, and constants to demonstrate their usage in Rust. Understanding these concepts is essential for effective variable management in Rust programs.

## Does shadowing works on const as well?

No, shadowing does not work on constants (`const`) in Rust. **Once a constant is defined, its value cannot be changed or shadowed.** Constants have a fixed, unchangeable value throughout the scope of their existence.

```rust
const MAX_POINTS: u32 = 100_000;

// Uncommenting the line below would result in a compilation error
// const MAX_POINTS: u32 = 200_000; // cannot redeclare `MAX_POINTS`
```

Attempting to redeclare or shadow the constant `MAX_POINTS` with a new value will cause a compilation error. If you need a variable with a changeable value, use a mutable variable instead of a constant.

## Conclusion

Variables and mutability are fundamental concepts in Rust that play a crucial role in how code is written and managed. By understanding how variables work in Rust, you can write safer, more efficient code that takes full advantage of Rust's unique features.