typestar

Returning Result from main in Rust

main can return a Result, and the runtime reports the error for you.

use std::error::Error;

fn checked_div(a: i32, b: i32) -> Result<i32, String> {
    if b == 0 {
        return Err("divide by zero".to_string());
    }
    Ok(a / b)
}

fn main() -> Result<(), Box<dyn Error>> {
    let value = checked_div(84, 2)?;
    println!("{value}");

    let total: i32 = "21".parse()?;
    println!("{}", total * 2);
    Ok(())
}

How it works

  1. The signature becomes Result<(), Box<dyn Error>>.
  2. An Err prints the Debug form and exits non-zero.
  3. This is how ? reaches the top level of a program.

Keywords and builtins used here

The run, in numbers

Lines
17
Characters to type
313
Tokens
118
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 71 seconds.

Type this snippet

Step 4 of 4 in Result & the ? operator, step 7 of 15 in Error handling.

← Previous Next →