Skip to content

Flag with optional value is parsed differently from getopt_long #49

@kornelski

Description

@kornelski

When using C getopt_long a long option with optional_argument will have a value only if --flag=value syntax is used. --flag arg is parsed as a flag without an argument, and a free argument (I've verified that on macOS and Linux/glibc).

getopts' optflagopt behaves differently. It always takes the next argument as the value, even if the = syntax is not used.

This is problematic for me, because I can't faithfully port C getopt_long program to Rust. I also think it's a less useful behavior, because it makes it impossible to set a optflagopt flag without a value if it's not the last/only argument.

extern crate getopts;

fn main() {
    let mut o = getopts::Options::new();
    o.optflagopt("", "value", "", "");
    
    let m = o.parse(&["--value", "foo", "bar"]).unwrap();
    println!("with space {:?} + {:?}", m.opt_str("value"), m.free);

    let m = o.parse(&["--value=foo", "bar"]).unwrap();
    println!("with = {:?} + {:?}", m.opt_str("value"), m.free);
}

This prints:

with space Some("foo") + ["bar"]
with = Some("foo") + ["bar"]

I'd prefer it to parse as:

with space None + ["foo", "bar"]
with = Some("foo") + ["bar"]

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions