Skip to content

Commit 0df59e2

Browse files
Variables, Mut & Shadowing
1 parent 9abf5da commit 0df59e2

2 files changed

Lines changed: 51 additions & 2 deletions

File tree

examples/01_variables.rs

Lines changed: 48 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,58 @@
1+
// TO RUN THE EXAMPLE : cargo run --example 01_variables
2+
13
fn main() {
24

3-
// Part 1 : Immutable vs Mutable Variables
5+
// PART 1 : Immutable vs Mutable Variables
46
let x = 5;
57
let mut y = 10;
68
y = 20 ;
79

810
println!("x = {} ", x);
911
println!("y = {} ", y);
1012

11-
//
13+
// PART 2 : Data Types
14+
15+
let age: u32 = 25; // unsigned 32-bit integer -- can't be negative
16+
let count: i32 = 100; // signed 32=bit integer -- can be negative or positive
17+
let big: i64 = 1_000_000; // underscores make numbers readable
18+
let pi: f64 = 3.14159; // float
19+
let flag: bool = true; // boolean
20+
let letter: char = 'A'; // character
21+
let name: &str = "Hitesh Bhatnagar"; // fixed text known at compile time
22+
23+
let greeting: String = String::from("Hello, Universe"); // owned text - flexible
24+
25+
// PART 3: Shadowing
26+
27+
// shadowing allows redeclare a variable with the same name
28+
// Each let x creates a BRAND NEW VARIABLE
29+
let x = 5;
30+
let x = x*2; // new x created, old x is deleted
31+
let x = x+3; // another new x
32+
33+
println!("Shadowed x = {}", x); // 13
34+
35+
let spaces = " "; // &str type
36+
let spaces = spaces.len(); // now usize ( a number ) -- totally fine
37+
println!("spaces = {}", spaces); // 3
38+
39+
// PART 4: mut V/S Shadowing
40+
41+
let mut score = 0;
42+
score = 20;
43+
println!(" score = {}", score);
44+
45+
// Shadowing => Creates new variable, can change VALUE & TYPE
46+
let status = "inactive";
47+
println!("status = {}", status);
48+
let status = true; // changes type from &str to bool
49+
println!("status = {}", status);
50+
51+
// PART5 : Constants
52+
53+
const euler_num: f32 = 2.71828;
54+
println!("Max euler_num= {}", euler_num );
55+
56+
57+
1258
}

src/main.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
fn main(){
2+
println!("Happy Learning :)")
3+
}

0 commit comments

Comments
 (0)