Control Flow
Understand control flow and numeric operators in Rust. You will create the FizzBuzz program using Rust!
Numeric operators
+addition-subtraction/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
iis a multiple of3, printFizz - when
iis a multiple of5, printBuzz - when
iis a multiple of both3and5, printFizzBuzz
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");
}
}