Rust for the Novice Programmer/Basic Maths Testing Program/Checking the Numbers
Checking the numbers
[edit | edit source]Now, we wish to verify whether the number the user inputted is equal to the result of the operator on the two numbers. First, let's calculate the number. To do this, it makes sense to have the two numbers and the operator as part of a struct, since those 3 values are all used together often and it is convenient to have them all together so we can define functions on the struct for cleaner code. Let's define the struct like so:
struct MathsQuestion { left: i32, right: i32, operator: Operator, }
Often with structs, it is convenient to define a new() function that makes it convenient to construct the struct. We can do this like so:
impl MathsQuestion { fn new(left: i32, right: i32, operator: Operator) -> MathsQuestion { MathsQuestion { left, right, operator, } } }
Note that since the names of the variables are the same as the names of the fields in the struct, we don't need to write out
left: left, right: right, operator: operator,
This is a nice convenience. Also we are using implicit return with no semicolon, so we don't need to write return.
Now we can change our print_question() function to be a method on this new struct, so we add the following function inside the impl MathsQuestion {} block:
fn print(&self) { println!("What is {} {} {}?", self.left, self.operator, self.right); }
Now we can write a function on the MathsQuestion struct to calculate the result, this function is again inside the impl MathsQuestion {} block:
fn calc_result(&self) -> i32 { match self.operator { Operator::Addition => self.left + self.right, Operator::Subtraction => self.left - self.right, } }
And now we can change our main() function to:
fn main() { let question = MathsQuestion::new(35, 23, Operator::Subtraction); question.print(); let val = wait_for_input(); let result = question.calc_result(); if val == result { println!("You got it correct! Well done!"); } else { println!("Incorrect! The correct answer was {}", result); } }
And now it works! If we enter 12(which is 35 - 23) we get the correct message, if we enter any other number we get the incorrect message!
Next: We make the generated numbers random using external crates