61 lines
1.3 KiB
Rust
61 lines
1.3 KiB
Rust
const THREE_DAYS_IN_SECONDS : u32 = 3 * 24 * 60 * 60;
|
|
|
|
fn main() {
|
|
println!("
|
|
1/ A constant can be defined outside main,
|
|
and be called from main:
|
|
|
|
---RUNNING THE CODE");
|
|
println!("const THREE_DAYS_IN_SECONDS: {THREE_DAYS_IN_SECONDS}
|
|
---END OF EXECUTION");
|
|
|
|
println!("
|
|
2/ A variable is mutable only if you use mut. Ex:
|
|
let mut x = 5;
|
|
|
|
---RUNNING THE CODE");
|
|
|
|
let mut x = 5;
|
|
println!("x (defined by 'let mut') is {x}");
|
|
x = 6;
|
|
println!("x is now {x}
|
|
---END OF EXECUTION");
|
|
|
|
|
|
println!("
|
|
3/ Instead of allowing mutability,
|
|
a variable can be 'shadowed'.
|
|
It means we redefine a new variable
|
|
on the same namespace. Ex:
|
|
let shadow = 7
|
|
let shadow = shadow + 3
|
|
|
|
---RUNNING THE CODE");
|
|
let shadow = 7;
|
|
println!("shadow is {shadow}");
|
|
|
|
let shadow = shadow +3;
|
|
println!("shadow is {shadow}");
|
|
|
|
{
|
|
let shadow = shadow + 10;
|
|
println!("shadow in scope is {shadow}");
|
|
}
|
|
println!("shadow back outside scope is {shadow}
|
|
---END OF EXECUTION");
|
|
|
|
println!("
|
|
4/ shadowing even allows to
|
|
change the type of the variable!
|
|
|
|
---RUNNING THE CODE");
|
|
let secret = "xxxx";
|
|
println!("secret is {secret}");
|
|
|
|
let secret = secret.len();
|
|
println!("secret - now defined with secret.len() -
|
|
is now: {secret}
|
|
---END OF EXECUTION");
|
|
}
|
|
|