Good way to handle not given command line arguments?

Hi.

I'm writing some codes to make a configuration struct instance from command line arguments.

Some args will be given or not, so I need to handle this.
This is a way which I thought roughly.

struct Configuration {
    given_or_not: Option<i32>,
}
// ...
// code for making ArgMatches is omitted here
// ...

let mut args = parse_args(); // <- got ArgMatches

fn make_config(args: &mut ArgMatches) -> Configuration {
    Configuration {
         given_or_not: args.get_one::<i32>("given_or_not"),
    }
}

Is this enough? or can I just assign the field with default using unwrap_or_default()?

Could you tell me how you handle this situation?
Thanks.

1 Like

I would use unwrap_or_default (or unwrap_or, etc) so the field can be just i32 instead of Option<i32>. That way the field is not an Option and does not have to be checked later.

2 Likes

it depends on what's your intended semantic. if your program would behave differently whether the argument is given or not, you have to make the distinction, so use Option<i32>. if, however, your program has a default value for the argument, you should make the struct field a i32 and use unwrap_or()/unwrap_or_default() instead.

example of Option<i32>:

# set timeout to 0 milliseconds, i.e. immediately return if not ready
./run --timeout 0
# without timeout, wait forever until ready
./run

example of i32 with default value of 10

# set timeout to 10 miliseconds
./run --timeout 10
# exactly same as above, because 10 is the default
./run
2 Likes

You should probably use a command line argument parser library that allows you to specify such common behavior declaratively by default. See eg. clap::Parser.

4 Likes