v0.0.1 chap3.1 variables and mutability

This commit is contained in:
Florian Roger 2026-05-06 02:43:36 +02:00
parent bd64f9f874
commit 5bff9ae8ab
4 changed files with 74 additions and 0 deletions

1
variables/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/target

7
variables/Cargo.lock generated Normal file
View File

@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "variables"
version = "0.1.0"

6
variables/Cargo.toml Normal file
View File

@ -0,0 +1,6 @@
[package]
name = "variables"
version = "0.1.0"
edition = "2024"
[dependencies]

60
variables/src/main.rs Normal file
View File

@ -0,0 +1,60 @@
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");
}