What's the proper way to use std.getopt?

Adam D. Ruppe destructionator at gmail.com
Mon Dec 11 23:55:17 UTC 2017


On Monday, 11 December 2017 at 20:58:25 UTC, Jordi Gutiérrez 
Hermoso wrote:
> I don't quite understand what to do if getopt throws. I would 
> have hoped for something like

I might have already said this to you on IRC but the way I'd do 
it (if you must do this) is:

void main(string[] args) {
     int arg1;
     string arg2;

     bool getoptions(string[] args) {
        auto result = getopt(args, "opt1", "docstring 1", &arg1, 
"opt2", "docstring 2", &arg2);
        if(result.helpWanted)
          defaultGetoptPrinter("Some information about the 
program.", result.options);
        return result.helpWanted;
     }

     try {
        if(getoptions(args))
             return; // it just printed help
     } catch(GetOptException e) {
        writeln(e.msg);
        getoptions(["--help"]);
        return;
     }

     /* rest of your program */
}



Even though, I think printing the whole help output on any 
exception is likely to be fairly annoying since it obscures the 
actual error message.


More information about the Digitalmars-d-learn mailing list