Originally published on php2rust.dev — part of the PHP to Rust course. View this lesson on the original site.

Here is one clean solution for the Smart User Input Classifier exercise.

Rust solution

fn classify_value(n: i32) -> (&'static str, &'static str) {
    let sign = if n > 0 {
        "positive"
    } else if n < 0 {
        "negative"
    } else {
        "zero"
    };

    let parity = if n % 2 == 0 { "even" } else { "odd" };
    (sign, parity)
}

fn main() {
    let inputs: Vec<Option<i32>> = vec![Some(12), None, Some(0), Some(-3), Some(101), None];

    let mut some_count = 0;
    let mut none_count = 0;
    let mut positive_count = 0;
    let mut even_count = 0;

    for input in inputs {
        match input {
            Some(n) => {
                some_count += 1;
                let (sign, parity) = classify_value(n);
                if n > 0 {
                    positive_count += 1;
                }
                if n % 2 == 0 {
                    even_count += 1;
                }

                println!("value={} => {}, {}", n, sign, parity);
            }
            None => {
                none_count += 1;
                println!("missing input");
            }
        }
    }

    println!("\nSummary:");
    println!("Some: {}", some_count);
    println!("None: {}", none_count);
    println!("Positive: {}", positive_count);
    println!("Even: {}", even_count);
}

Why this works

  • Uses match to force handling both Some and None
  • inputs is Vec<Option<i32>>, so each entry must be either Some(number) or None (plain 12 would be an i32, not an Option<i32>)
  • Uses counters to build the final summary
  • Separates number classification into a helper function for clarity

What's next

Next: Chapter 2 quiz.

From PHP to Rust — Rust Syntax and Functions