Rust Variables and Mutability Explained

iamdipankarpaul

Dipankar Paul

Posted on March 12, 2024

Rust Variables and Mutability Explained

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:

let x = 5; // immutable variable
Enter fullscreen mode Exit fullscreen mode

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

let mut y = 10; // mutable variable
y = 15; // valid because y is mutable
Enter fullscreen mode Exit fullscreen mode

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:

let message: &str = "Hello, Rust!"; // type annotation for a string reference
Enter fullscreen mode Exit fullscreen mode

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:

let z = "20"; // &str type
// shadows the previous z
let z: i32 = z.parse().unwrap(); // number type
Enter fullscreen mode Exit fullscreen mode

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:

const PI: f64 = 3.14;
Enter fullscreen mode Exit fullscreen mode

Example Combining Mutability, Shadowing, and Constants

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);
}
Enter fullscreen mode Exit fullscreen mode

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.

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`
Enter fullscreen mode Exit fullscreen mode

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.

💖 💪 🙅 🚩
iamdipankarpaul
Dipankar Paul

Posted on March 12, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related