[go: up one dir, main page]

Control Flows

if - else if - else

if

let age = 13;

if age < 18 {
    println!("Hello, child!"); // The code prints this
}

if else

let i = 7;

if i % 2 == 0 {
    println!("Even");
} else {
    println!("Odd"); // The code prints this
}

With let Statements

let age: u8 = 13;
let is_below_eighteen = if age < 18 { true } else { false }; // true

if else if else

i. A simple example,

let team_size = 7;

if team_size < 5 {
    println!("Small");
} else if team_size < 10 {
    println!("Medium"); // The code prints this
} else {
    println!("Large");
}

ii. Let’s refactor the above code,

let team_size = 7;
let team_size_in_text;

if team_size < 5 {
    team_size_in_text = "Small";
} else if team_size < 10 {
    team_size_in_text = "Medium";
} else {
    team_size_in_text = "Large";
}

println!("Current team size : {}", team_size_in_text); // Current team size : Medium

iii. Let’s refactor further (variable shadowing),

let team_size = 7;
let team_size = if team_size < 5 {
    "Small" // โญ๏ธ no ;
} else if team_size < 10 {
    "Medium"
} else {
    "Large"
};

println!("Current team size : {}", team_size); // Current team size : Medium

โญ๏ธ Return data type should be the same on each block when using this as an expression.

match

With Multiple Patterns

let tshirt_width = 20;
let tshirt_size = match tshirt_width {
    13 => "XS",     // check 13
    14 | 15 => "S", // check 14 and 15
    16..18 => "M",  // check from 16 to 17 / 18 exclusive (16,17)
    18..=20 => "L", // check from 18 to 20 (18,19,20)

    x if x > 20 && x < 26 => "XL", // check 21 to 25 (21,22,23,24,25)
    // >,>=,<,<= via assigning the value to a variable (x) + if

    _ => "Not Available", // default behavior, if none of conditions matches
};

println!("{}", tshirt_size); // L

Without Default Behavior

let is_allowed = false;
let list_type = match is_allowed {
    true => "Full",
    false => "Restricted"
    // no default/ _ condition can be skipped
    // Because data type of is_allowed is boolean and all possibilities checked on conditions
};

println!("{}", list_type); // Restricted

With Multiple Variable Matchings

let marks_paper_a: u8 = 25;
let marks_paper_b: u8 = 30;

let output = match (marks_paper_a, marks_paper_b) {
    (50, 50) => "Full marks for both papers",
    (50, _) => "Full marks for paper A",
    (_, 50) => "Full marks for paper B",
    (x, y) if x > 25 && y > 25 => "Good",
    (_, _) => "Work hard"
};

println!("{}", output); // Work hard

loop

Infinite loop

// โš ๏ธ This will run forever without terminating. Termininate manually (Ctrl+C)
loop {
    println!("Loop forever!");
}

With break and continue

let mut a = 0;

loop {
    if a == 0 {
        println!("Skip Value : {}", a);
        a += 1;
        continue;
    } else if a == 2 {
        println!("Break At : {}", a);
        break;
    }

    println!("Current Value : {}", a);
    a += 1;
}

Returning a Value with break

let (mut x, y) = (1, 10);

let z = loop {
    x *= 2; // x = 2,4,8,16...

    if x >= y { // 16 >= 10, so return 16
        break x;
    }
};

println!("{z}"); // 16

Labeling and break the Outer loop

let mut b1 = 1;

'outer: loop { // set label outer (or any other snake_case name)
    let mut b2 = 1;

    'inner: loop { // set label inner
        println!("Current Value : [{}][{}]", b1, b2);

        if b1 == 2 && b2 == 2 {
            break 'outer; // kill outer loop
        } else if b2 == 5 {
            break;
        }

        b2 += 1;
    }

    b1 += 1;
}

while

Infinite while

// โš ๏ธ This will run forever without terminating. Termininate manually (Ctrl+C)
while true {
    println!("While forever!");
}

A simple while

let mut a = 1;

while a <= 10 {
    println!("Current value : {}", a);
    a += 1; //no ++ or -- on Rust
}

With break and continue

let mut b = 0;

while b < 5 {
    if b == 0 {
        println!("Skip value : {}", b);
        b += 1;
        continue;
    } else if b == 2 {
        println!("Break At : {}", b);
        break;
    }

    println!("Current value : {}", b);
    b += 1;
}

// ๐Ÿ’ก You can't break with a value in a while

Labeling and break the Outer while

let mut c1 = 1;

'outer: while c1 < 6 { // set label outer (or any other snake_case name)
    let mut c2 = 1;

    'inner: while c2 < 6 { // set label inner
        println!("Current Value : [{}][{}]", c1, c2);

        if c1 == 2 && c2 == 2 {
            break 'outer; // kill outer while
        }

        c2 += 1;
    }

    c1 += 1;
}

for

A simple for

// 0 to 10 (10 exclusive); In other languages, `for(i = 0; i < 10; i++)`
for i in 0..10 {
    println!("Current value : {}", i);
}
// 1 to 10 (10 inclusive); In other languages, `for(i = 1; i <= 10; i++)`
for i in 1..=10 {
    println!("Current value : {}", i);
}

With break and continue

// ๐Ÿ’ก You can't break with a value in a for
for b in 0..6 {
    if b == 0 {
        println!("Skip Value : {}", b);
        continue;
    } else if b == 2 {
        println!("Break At : {}", b);
        break;
    }

    println!("Current value : {}", b);
}

Labeling and break the Outer for

'outer: for c1 in 1..6 { // set label outer (or any other snake_case name)

    'inner: for c2 in 1..6 { // set label inner
        println!("Current Value : [{}][{}]", c1, c2);

        if c1 == 2 && c2 == 2 {
            break 'outer; // kill outer for
        }
    }
}

With Arrays and Vectors

let group : [&str; 4] = ["Mark", "Larry", "Bill", "Steve"];

// ๐Ÿ‘Ž group.len() = 4 check on each iteration of the for loop
for n in 0..group.len() {
    println!("Current Person : {}", group[n]);
}

// ๐Ÿ‘ group.iter() turn the array into a simple iterator
for person in group.iter() {
    println!("Current Person : {person}");
}

// ๐Ÿ‘ group.iter().enumerate() helps to read both the current index (starting from zero) and the value
for (index, person) in group.iter().enumerate() {
    println!("Person {index} : {person}");
}

With a Vector of Tuples

let list = vec![(1, "Mark"), (2, "Larry"), (3, "Steve")];

for (index, person) in list {
    println!("Person {index} : {person}");
}