CodeBlanks Logo Icon CodeBlanks

Computing

Compute the result with trim, parse and arithmetic operations.

Computation

Because the pieces are text, they are converted to numbers with parse; the operator symbol is chosen with match:

fn hesapla(a: f64, op: &str, b: f64) -> Result<f64, String> {
    match op {
        "+" => Ok(a + b),
        "-" => Ok(a - b),
        "*" => Ok(a * b),
        "/" => Ok(a / b),
        _ => Err(format!("bilinmeyen işlem: {op}")),
    }
}

The _ arm catches all other cases; Rust requires match to cover every possibility.

Converting to numbers

"12".parse::<f64>() returns a Result<f64, ParseFloatError>. To convert the error message into our own format, map_err is used:

let a: f64 = "12".parse().map_err(|_| "geçersiz sayı".to_string())?;

The ? operator returns the error to the caller immediately if there is one; otherwise it gives the inner value. This avoids writing nested matches.

Practice The calculator function

Write the hesapla function above with the four operations and the _ arm. Print the results of hesapla(12.0, "*", 3.0) and hesapla(2.0, "^", 3.0) with {:?} on separate lines.

Starter code

main.rs
fn main() {
    // buraya yaz
}

Sample solution

main.rs
fn hesapla(a: f64, op: &str, b: f64) -> Result<f64, String> {
    match op {
        "+" => Ok(a + b),
        "-" => Ok(a - b),
        "*" => Ok(a * b),
        "/" => Ok(a / b),
        _ => Err(format!("bilinmeyen işlem: {op}")),
    }
}

fn main() {
    println!("{:?}", hesapla(12.0, "*", 3.0));
    println!("{:?}", hesapla(2.0, "^", 3.0));
}

Expected output

Ok(36.0)
Err("bilinmeyen işlem: ^")

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What happens if you remove the <code>_</code> arm from the <code>match</code>?

  • On an unknown operator the program silently continues
  • A run-time panic
  • Nothing happens
  • Compile error: not all possibilities are covered Correct answer

Explanation: Rust checks at compile time that a match is exhaustive; since a &str has infinitely many values, _ is needed.

2 Default arm

Question
match op {
    "+" => Ok(a + b),
    ____ => Err("bilinmeyen".to_string()),
}
Answer
match op {
    "+" => Ok(a + b),
    _ => Err("bilinmeyen".to_string()),
}

Explanation: The _ arm catches every value that didn't match.

3 Input and result

Term Meaning
(12, "*", 3) Ok(36)
(7, "/", 2) Ok(3.5)
(2, "^", 3) Err(unknown operator)
"x".parse::<f64>() Err

All lessons in Beginner