Defining a Variable in Rust

In Rust, variables are defined using the let keyword. Rust is a statically typed language, which means that the type of a variable must be known at compile time. However, Rust also supports type inference, allowing the compiler to determine the type based on the assigned value.

Basic Variable Declaration

To declare a variable, you use the let keyword followed by the variable name and an optional type annotation. By default, variables in Rust are immutable, meaning their values cannot be changed once assigned.

Example of Basic Variable Declaration


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

Mutable Variables

If you want to change the value of a variable after it has been defined, you need to declare it as mutable using the mut keyword. This allows you to modify the variable's value later in the code.

Example of Mutable Variable


fn main() {
let mut y = 10; // Mutable variable
println!("The initial value of y is: {}", y); // Output: The initial value of y is: 10

y += 5; // Modify the value of y
println!("The modified value of y is: {}", y); // Output: The modified value of y is: 15
}

Type Annotations

While Rust can infer the type of a variable, you can also specify the type explicitly. This is useful for clarity or when the type cannot be inferred from the context.

Example of Type Annotation


fn main() {
let a: i32 = 42; // Explicit type declaration
let b: f64 = 3.14; // Floating-point number

println!("a: {}, b: {}", a, b); // Output: a: 42, b: 3.14
}

Constants

In addition to variables, Rust also supports constants, which are defined using the const keyword. Constants are always immutable and must have a type annotation. They can be declared in any scope, including global scope.

Example of Constants


const PI: f64 = 3.14159; // Constant declaration

fn main() {
println!("The value of PI is: {}", PI); // Output: The value of PI is: 3.14159
}

Conclusion

Defining variables in Rust is straightforward, using the let keyword for immutable variables and let mut for mutable ones. Rust's type system allows for both type inference and explicit type annotations, providing flexibility and safety in variable management. Understanding how to define and use variables is fundamental to programming in Rust.