Optional parameters?

Seb seb at wilzba.ch
Sun Apr 1 22:34:16 UTC 2018


On Sunday, 1 April 2018 at 15:54:16 UTC, Steven Schveighoffer 
wrote:
> I currently have a situation where I want to have a function 
> that accepts a parameter optionally.
>
> I thought maybe Nullable!int might work:
>
> void foo(Nullable!int) {}
>
> void main()
> {
>    foo(1); // error
>    int x;
>    foo(x); // error
> }
>
> Apparently, I have to manually wrap an int to get it to pass. 
> In other languages that support optional types, I can do such 
> things, and it works without issues.
>
> I know I can do things like this:
>
> void foo(int x) { return foo(nullable(x)); }
>
> But I'd rather avoid such things if possible. Is there a way 
> around this? Seems rather limiting that I can do:
>
> Nullable!int x = 1;
>
> but I can't implicitly convert 1 to a Nullable!int for function 
> calls.
>
> -Steve

My workaround is to use struct initialization:

---
import std.stdio, std.typecons;

static struct FooConfig
{
     Nullable!int a;
}

void foo(FooConfig optionalConfig = FooConfig.init)
{
     optionalConfig.writeln;
}

void main()
{
     foo();

     FooConfig params = {
        a: 42,
     };
     foo(params);
     //foo(FooConfig(42)); // <- hehe, no implicit conversion
}
---

https://run.dlang.io/is/HvN701

I know the separate line and variable is annoying.
With the in-place struct-initialization DIP 
(https://github.com/dlang/DIPs/pull/71), it would become sth. 
like:

foo(FooConfig({a : 42}));
foo(FooConfig{a : 42});

(syntax is not clear yet and I still haven't gotten around 
implementing this in DMD)


More information about the Digitalmars-d-learn mailing list