Basics

Rust Variables

Declaring Rust Variables

Rust variables use let and mut for immutability and mutability.

Introduction to Rust Variables

In Rust, variables are fundamental building blocks for storing data. Understanding how to declare and use variables is crucial for writing Rust programs. Rust emphasizes safety and performance, and its variable system reflects these values through immutability by default.

Immutable Variables with let

By default, variables in Rust are immutable. This means once a value is bound to a variable, it cannot be changed. This immutability ensures that variables are safe from unintended modifications, leading to more predictable and stable code.

To declare an immutable variable, you use the let keyword:

In this example, x is an immutable variable bound to the value 5. Any attempt to change x after its initial assignment will result in a compile-time error.

Mutable Variables with mut

If you need a variable whose value can change, you must explicitly declare it as mutable using the mut keyword. This allows the variable's value to be updated after its initial assignment.

Here's how you can declare a mutable variable:

In this example, y is declared as mutable, allowing its value to be changed from 10 to 15. The mut keyword is crucial for enabling this mutability.

Shadowing Variables

Rust also supports variable shadowing, which allows you to declare a new variable with the same name as a previous variable. This is especially useful when you need to transform a value without mutating it directly.

Here's an example of shadowing:

In this example, z is initially assigned the value 5. The let z = z + 1; statement shadows the previous z, resulting in a new variable with the value 6. This technique is useful for transformations and temporary changes.

Conclusion

Rust variables are designed with safety and performance in mind. By default, variables are immutable, promoting stability and predictability in your programs. When mutability is necessary, the mut keyword allows you to express this intention clearly. Additionally, shadowing offers flexibility in variable transformations without side effects. Understanding these principles is essential for effectively managing data in Rust.

Previous
Syntax