2
\$\begingroup\$

I want to get the first argument as a number, if there is any. This does not feel quite right, but I don't know yet what the Rust way would be.

I'm not searching for a args-framework or something, I just want to get a grip on doing stuff with Rust.

fn limit_from_args(args: env::Args) -> i32 {
    let args: Vec<String> = args.collect();
    if args.len() > 1 {
        match args[1].parse::<i32>() {
            Ok(i) => i + 1,
            Err(_) => 101,
        }
    } else {
        101
    }
}
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

There's always multiple ways to solve a problem, but if we keep your function signature unchanged, I'd probably write something like:

use std::env;

fn limit_from_args(mut args: env::Args) -> i32 {
    args.nth(1).and_then(|v| v.parse().ok()).unwrap_or(101)
}

fn main() {}

Notable things with your first solution:

  1. There's no need to specify the String type when collecting; you can just use Vec<_>.
  2. Since only one argument is needed, the code will be more efficient if that's all we look at. If there were thousands of arguments, there's no need to allocate space for 99% of them and then throw that away.
  3. If you did have a slice or a vector, you can combine the range check and getting the value into one call with slice::get. This avoids the extra overhead of checking the index against the range:

    match args.get(1) {
        Some(val) => ...,
        None => ...,
    }
    
  4. There's probably no need to specify the type for parse, it should be inferred from the return type.

  5. Since the error codes are repeated, they should probably be extracted to a constant with a meaningful name. Even if they weren't repeated, 101 looks like a magic number.
\$\endgroup\$
1
  • \$\begingroup\$ Pretty cool! Exactly what I was looking for, thank you so much, kind sir! I'll read through it and try it out. I tried binding 101 to a variable, but that didn't work out because just typing the variable instead of the 101 brought me an error. \$\endgroup\$
    – user101049
    Commented Mar 23, 2016 at 21:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.