In Rust, variables are the basic units for storing data, and their declaration and usage follow unique ownership and borrowing rules to ensure memory safety and concurrency safety. Unlike other languages, Rust variables are immutable by default, which helps prevent accidental data modifications.
Variable Declaration
Use the let keyword to declare a variable, with the basic syntax: let variable_name = value;. For example, declaring an integer variable:
let x = 5;
println!("{}", x);
// Output: 5
Note: Rust variables are immutable by default, meaning they cannot be reassigned once a value is assigned. Attempting to modify x will result in a compilation error.
Mutable Variables
To declare a mutable variable, use the let mut keyword. This allows modifying the variable's value, for example:
let mut y = 10;
y = 20;
println!("{}", y);
// Output: 20
Mutable variables are very useful when data needs to be updated, but should be used cautiously to avoid data races.
Variable Types and Inference
Rust is a statically typed language, but the compiler can usually infer types automatically. You can explicitly specify the type, such as: let z: i32 = 30;. The following example demonstrates type inference:
let a = 3.14; // Inferred as f64
let b = true; // Inferred as bool
println!("a: {}, b: {}", a, b);
// Output: a: 3.14, b: true
Warning: If the type is ambiguous, the compiler will report an error. For example, let c = 42; might be inferred as i32, but in some contexts, explicit typing is required.
Variable Scope and Ownership
Variable scope starts from the point of declaration and ends at the block where it is located. Rust's ownership system ensures that each value has only one owner, preventing memory leaks. Example:
{
let s = String::from("hello");
println!("{}", s);
} // s is dropped here, memory is freed
// println!("{}", s); // Error: s is out of scope
Ownership rules are a core feature of Rust, and understanding them is crucial for efficient programming.
Variable Usage Examples
Variables can be used for various operations, such as arithmetic operations, conditional judgments, and function calls. Here is a comprehensive example:
let mut count = 0;
count += 1;
if count > 0 {
println!("Count is positive: {}", count);
}
// Output: Count is positive: 1
When using variables, ensure to follow borrowing rules, for example, immutable references allow multiple to exist simultaneously:
let data = 100;
let ref1 = &data;
let ref2 = &data;
println!("ref1: {}, ref2: {}", ref1, ref2);
// Output: ref1: 100, ref2: 100