let
keyword is used to define a variable in Rust.
fn main() {
let name = "Bruce";
println!("Hello, {}", name);
}
We can define as many variables as we want using let
. But, we need to use them once defined. Otherwise, compiler will throw a warning (not error) as unused variables.
fn main() {
let name = "Bruce";
let age = 29;
println!("Hello, {}", name);
}
Even further, compiler also suggests the variable to prefix with _
if variable is defined in this way (defined but no plan to use for now) to remove the warning.
let
actually create an immutable variable. In other words, you can't change the value of it once defined. You'll get an error about assigning the value to immutable variable.
fn main() {
let x = 12;
x = 13;
println!("{}", x);
}
If we're intentionally plan to change the value as suggested above, we need to mut
the variable.
fn main() {
let mut x = 12;
x = 13;
println!("{}", x);
}
But, this again throw a warning about unused assignment as value 12 that is assigned in above program is re-assigned again before it actually used. So, assigning 12 is useless.
Labels: rust