diff --git a/variables/.gitignore b/variables/.gitignore new file mode 100644 index 0000000..ea8c4bf --- /dev/null +++ b/variables/.gitignore @@ -0,0 +1 @@ +/target diff --git a/variables/Cargo.lock b/variables/Cargo.lock new file mode 100644 index 0000000..f26e54f --- /dev/null +++ b/variables/Cargo.lock @@ -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" diff --git a/variables/Cargo.toml b/variables/Cargo.toml new file mode 100644 index 0000000..c093eb6 --- /dev/null +++ b/variables/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "variables" +version = "0.1.0" +edition = "2024" + +[dependencies] diff --git a/variables/src/main.rs b/variables/src/main.rs new file mode 100644 index 0000000..18ba783 --- /dev/null +++ b/variables/src/main.rs @@ -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"); +} +