Jump to content

Rust for the Novice Programmer/Basic Maths Testing Program/Getting Started

From Wikibooks, open books for an open world

Getting Started with our Maths Program

[edit | edit source]

Let's start a new program by going to a new folder in the terminal and typing 'cargo init'. Then we can open up main.rs in the src/ folder. Let's start off by writing a function to take in the numbers and print out the question to the terminal.

fn print_question(num1: i32, num2: i32) {
    println!("What is {} + {}?", num1, num2);
}

And in our main function, we call it like so:

fn main() {
    print_question(35, 23);
}

And if we run this now with 'cargo run' we get

What is 20 + 30?

in the terminal.

However, this only works with addition. Let's make it work for both addition and subtraction. To represent the mathematical operator, we need something that can be one of a number of options. The perfect way to represent this is with an enum. So we create our enum as follows:

enum Operator {
    Addition,
    Subtraction,
}

Now, to display the operator, we can match against the operator and select the character for it, so we change our print_question() function as follows:

fn print_question(num1: i32, num2: i32, operator: Operator) {
    let operator_string = match operator {
        Operator::Addition => "+",
        Operator::Subtraction => "-",
    }; 
    println!("What is {} {} {}?", num1, operator_string, num2);
}

And we can change our main function to:

fn main() {
    print_question(35, 23, Operator::Subtraction);
}

And now when we run cargo run, we get

What is 35 - 23?

in the terminal.

Next: we introduce traits as a cleaner way to display the operator.