Search⌘ K
AI Features

Solution Review 2: Make a Calculator

Explore how to implement conditional logic in Rust by creating a calculator using if and match expressions. Understand controlling flow for operations like addition, subtraction, multiplication, division, and modulus, including handling division by zero and invalid inputs. Gain practical skills in managing complex conditional statements in Rust.

We'll cover the following...

Solution :

Rust 1.40.0
fn test(a: i32, operator: char ,b: i32) {
match operator {
'+' => {
println!("{}", a + b);
},
'-' => {
println!("{}", a - b);
},
'*' => {
println!("{}", a * b);
},
'/' => {
if b == 0{
println!("Division by 0 is undefined");
}
else {
println!("{}", a / b);
}
},
'%' => {
if b == 0{
println!("Mod 0 is undefined");
}
else {
println!("{}", a % b);
}
},
_ => println!("{}", "invalid operator"),
}
}
fn main(){
print!("3 + 2: ");
test(3,'+',2);
print!("3 - 2: ");
test(3,'-',2);
print!("3 * 2: ");
test(3,'*',2);
print!("3 / 2: ");
test(3,'/',2);
print!("3 % 2: ");
test(3,'%',2);
print!("3 ( 2: ");
test(3,'(',2);
print!("3 ( 0: ");
test(3, '/', 0)
}

Explanation

  • match construct

    A match construct is defined from line 2 to line 19.

    • On line 2, the match statement takes an operator variable.
      • On line 3, checks if the operator variable is equal to + then it displays the result of addition on line 4.
      • On line 6, checks if the operator variable is equal to - then it displays the result of subtraction on
...