4  Control Flow

Objective

Understand control flow and numeric operators in Rust. You will create the FizzBuzz program using Rust!

Numeric operators

  • + addition
  • - subtraction
  • * multiplication
  • / division
  • % remainder

Logical Operators:

Logical operators are quite similar to R. The difference is that these operations are not vectorised. Furthermore, in Rust, a logical is called bool for booleans. bools can take on only two values: true or false.

  • == check equality
  • != check inequality
  • ! negate a logical value
  • && logical AND comparison
  • || logical OR comparison

Control flow

Rust uses if, else, and else if statements just like R. Where each branch is delimted by curly braces.

Each branch of the if statement must return the same type. For this portion of the workshop, be sure to terminate each statement with ; inside of the if statement so that nothing (unit type) is returned.

if x == y {
  // do something
} else {
  // do something else
}

The key difference is that the use of parentheses is not necessary for the conditional statement.

Exercise

This exercise you will create the famous FizzBuzz program.

For this, create a variable i. The rules are:

  • when i is a multiple of 3, print Fizz
  • when i is a multiple of 5, print Buzz
  • when i is a multiple of both 3 and 5, print FizzBuzz

Solution

View solution
fn main() {
    // let i = 15; // FizzBuzz
    // let i = 3; // Fizz
    // let i = 5; // Buzz
    let i = 47; // Nothing
    if (i % 3 == 0) && (i % 5 == 0) {
        println!("FizzBuzz");
    } else if i % 3 == 0 {
        println!("Fizz");
    } else if i % 5 == 0 {
        println!("Buzz");
    }
}