読者です 読者をやめる 読者になる 読者になる

Error Handling #3

https://doc.rust-lang.org/book/error-handling.html

use std::env;すると、argv.nthで引数をとれる。 引数の有無でエラー判定するための方法。

use std::env;

fn ok_or<T, E>(option: Option<T>, err: E) -> Result<T, E> {
    match option {
        Some(val) => Ok(val),
        None => Err(err),
    }
}

fn double_arg(mut argv: env::Args) -> Result<i32, String> {
    argv.nth(1)
        .ok_or("Please give at least one argument".to_owned())
        .and_then(|arg| arg.parse::<i32>().map_err(|err| err.to_string()))
        .map(|n| 2 * n)
}

fn main() {
    match double_arg(env::args()) {
        Ok(n) => println!("{}", n),
        Err(err) => println!("Error: {}", err),
    }
}
$ cargo run
    Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs
     Running `target/debug/5_7_error_handling`
Error: Please give at least one argument
$ cargo run a
    Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs
     Running `target/debug/5_7_error_handling a`
Error: invalid digit found in string
$ cargo run 3
    Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs
     Running `target/debug/5_7_error_handling 3`
6