Sage-Code Laboratory
index<--

Rust Decision

Decision statements can be used to create multiple program branches that can be executed or not depending on results of logical expressions called condition.

Conditional

Conditional statement is based on {if, else} keywords. You can create two program branches. When a condition is true then first branch is executed. When the condition is false the other branch is executed. The else branch is optional but the first is mandatory.

decision

Conditional Execution


Example:

fn main() {
    let a = 10;
    let b = 10;

    if a == b {
        println!("a and b are equal"); //expected
    }
    else
    {
        println!("a and b are not equal"); //unexpected
    }
}

Notes:

Expression "if"

In many languages the decision is only a statement. In Rust the if is actually an expression that can have a result. The result is given by the value of the last expression in the block. This is specific to Rust and looks a little bit strange for programmer. Sometimes may be useful to think like this especially when there is no ternary operator like "?" used in other languages.

Example:

/* demo for conditional expression */
fn main() {
    let condition: bool = false; //boolean
    let number = if condition { 5 } else { 6 };
    println!("The value of number is: {}", number);
}

Note:

Ladder

In Python we use elsif keyword and in Julia we use elseif keyword to create a multi-deck decision. Here in Rust we do not have a such keywords. Instead you can use else if that are two keywords. This is possible in Rust due to lack of any symbol required after the "else". In Python after else you must use ":" but in Rust you can use a block { ... } or another if statement to for a multi-path decision block.

decision ladder

Decision Ladder


Example:

fn main() {
    use std::io;
    /* read a number */
    println!("enter a number:");
    let mut input = String::new();
    io::stdin().read_line(&mut input).unwrap();
    let number: i32 = input.trim().parse().unwrap();

    /* check number */
    if number % 2 == 0 {
            println!("this number is divisible by 2");
        } else if number % 3 == 0 {
            println!("this number is divisible by 3");
        } else if number % 5 == 0 {
            println!("this number is divisible by 5");
        } else if number % 7 == 0 {
            println!("this number is divisible by 7");
        } else {
            println!("this number is not divisible by 2,3,5 or 7");
    }
    println!("done");
}

Homework:Open this example and run it: ladder

Match

There is one more control statement that is very important in Rust. This will replace "switch" or "case" that is available in Julia and Level. The idea of this statement is simple. We create a structure to check several conditions. We execute one statement for witch the condition is true. The beauty of Rust is that this condition is verified such way that all cases are covered. If we do not cover all cases a compiler error will be generated. "match" is one of the most powerful things in Rust.

Example:

/* define enumeration */
enum Coin {
    Nickel,
    Dime,
    Quarter,
}

/* use "match" statement */
fn penny(coin: Coin) -> u32 {
    match coin {
        Coin::Nickel => 5,
        Coin::Dime => 10,
        Coin::Quarter => 25,
    }
}

/* test penny() function */
fn main() {
   use Coin::{Quarter, Dime, Nickel};
   println!("A quarter has {} penny",penny(Quarter));
   println!("A dime has {} penny",penny(Dime));
   println!("A Nickel has {} penny",penny(Nickel));
}

Notes:

  1. The match has a special syntax symbol: "=>" this is like a "result" and is not used in any other place in the language. The function result type has a similar symbol "->". I have no idea why the symbol is different. It could be the same in my opinion.
  2. The symbol "::" is used here to extract element members from Coin. In my opinion we could use ".". For some reason I do not like this symbol "::". In Level language we use "." for all membership operations.
  3. The last element into enumeration has a coma after it. "Quarter,". In my opinion this is not necessary. I have look twice in the manual and this is the syntax. I can't complain but looks bad.

Homework: This example is on repl.it. Open and run it: penny


Read next: Repetition