Getopt default int init and zero

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri May 19 06:33:01 PDT 2017


On Friday, May 19, 2017 12:09:38 PM PDT Suliman via Digitalmars-d-learn 
wrote:
> I would like to check if user specified `0` as getopt parameter.
> But the problem that `int`'s are default in `0`. So if user did
> not specified nothing `int x` will be zero, and all other code
> will work as if it's zero.
>
> In std.typecons I found Nullable that allow init int to zero. I
> tried to do:
>
> Nullable!int dateInterval;
>
> try
> {
>   auto helpInformation = getopt(args,
>   "interval|i",  "Interval of selection in dayes", &dateInterval
>   );
> }
>
> But I am getting error:

getopt really only supports built-in types. I'd suggest that you try setting
the int to a value other than zero that you don't expect the user to enter
(e.g. -1 or int.max) and check for that. Alternatively, you could use
string, and then convert it using std.conv.to, which certainly isn't as
nice, because getopt isn't doing the conversion for you, but whereas you
can't check for an empty int, you _can_ check for an empty string.

Adding support for Nullable to getopt sounds like a good enhancement request
though. This is a very valid use case that is not well-served at the moment,
and supporting Nullable doesn't require figuring out how to support
aribitrary user-defined types, which is a whole other can of worms.

https://issues.dlang.org

And of course, if you're brave enough to figure enough out about getopt's
internal's to implement it yourself and create a pull request, that would be
quite welcome. :)

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list