Rust for the Novice Programmer/Basic Maths Testing Program/Randomness and External crates

Randomness and External Crates

edit

It makes no sense to just ask the same question over and over again, so what we want to do is randomise the numbers and the operator that the user has to calculate the result of. However, we have an issue since generating random numbers isn't in the standard library. This means we have to use an external library to get what we want, this has some advantages and disadvantages:

Advantages

edit
  • More options, could find a library that has the right trade-off between simplicity/configurability/performance/integrability that you want.
  • Often less conservative about making changes so more likely to take risks and experiment.
  • Does more opinionated things about more specific operations.

Disadvantages

edit
  • Code isn't as rigorously checked, so is more likely(but not always) to be less secure, less performant, less consistent.
  • Code will most likely be much less well documented so it can be harder to find what you want.

These are just guidelines and there definitely are exceptional community made libraries but you should take care. Also libraries in Rust are called crates; the pun is that we are using cargo to ship crates :p . For our project, we are going to use the fastrand crate since it is very simple and fast and we don't need the bells and whistles of other crates. To do this, we open our project folder and open the 'Cargo.toml' file in a text editor. Inside you will see this:

[package]
name = "maths-problems"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

What we want to do is add under the [dependencies] line a new line that says

fastrand = "1.7"

Different crates have different versions so it is always good to specify what version of the crate we want to avoid confusion. Now if we run using cargo, we can see it will take a bit longer to compile since it has to download and compile the fastrand crate and all the crates it uses. It will still run the same since we haven't used fastrand for anything yet.

Using it is dead easy though, let's add a function that creates a random maths question:

//inside impl MathsQuestion
fn new_random() -> MathsQuestion {
    let left = fastrand::i32(-50..=50);
    let right = fastrand::i32(-50..=50);
    let operator = if fastrand::bool() {
        Operator::Addition
    } else {
        Operator::Subtraction
    };
    MathsQuestion::new(left, right, operator)
}

We use ranges to get the values for the fastrand::i32() function, between -50 and 50 inclusive. fastrand::bool() just returns a boolean with equal odds. Now we can use this in our main function to generate the question:

let question = MathsQuestion::new_random();

And now when we run it, we get random questions as we want!

Next: Full annotated source code and possible extensions