Rust variables
Created By: chatGPT
In Rust, variables are used to store data values. By default, variables are immutable, meaning once a variable is bound to a value, you cannot change that value. To make a variable mutable, you need to specify the
mut
keyword. Here’s how you can create both immutable and mutable variables in Rust:fn main() {
let x = 5; // Immutable variable
// x = 6; // This will cause a compile-time error
let mut y = 10; // Mutable variable
y = 12; // This is fine
println!("x: {}, y: {}", x, y);
}
You can also specify the data type of variables, although Rust can usually infer it. Here’s an example that shows different data types:
fn main() {
let a: i32 = 100; // 32-bit integer
let b: f64 = 3.14; // 64-bit float
let c: char = 'A'; // Character
let d: bool = true; // Boolean
println!("a: {}, b: {}, c: '{}', d: {}", a, b, c, d);
}
When declaring variables, you can also use constants for values that should never change. Constants are declared using the
const
keyword and must have an explicit type specified. Here’s an example:fn main() {
const MAX_POINTS: u32 = 100_000;
println!("The maximum points are: {}", MAX_POINTS);
}
Furthermore, Rust supports shadowing, which allows you to declare a new variable with the same name as a previous variable. This can be useful for transforming values. Here’s a simple example of shadowing:
fn main() {
let x = 5;
let x = x + 10; // `x` is now shadowed
println!("Shadowed x: {}", x);
}
A key concept in Rust is ownership, which determines how values are managed. When a variable goes out of scope, Rust automatically deallocates its memory. Take a look at this example demonstrating ownership:
fn main() {
let s1 = String::from("Hello");
let s2 = s1; // Ownership moves to s2
// println!("s1: {}, s2: {}"); // This will cause a compile-time error
println!("s2: {}", s2);
}