How to make a function that accepts optional struct but can accept struct literal too

SomeGuy someguy at mailinator.com
Fri Oct 15 21:01:57 UTC 2021


You could use `Nullable` from the standard library to achieve 
something similar, but it isn't as simple/nice as your C99 
compound literal example:

```D
import std.stdio;
import std.typecons; // 
https://dlang.org/phobos/std_typecons.html#Nullable

struct inputs_t { int x, y; };

void foo(Nullable!inputs_t optional_inputs)
{
     if (optional_inputs.isNull) {
         writeln("0 0");
     } else {
         auto non_null = optional_inputs.get;
         writeln(non_null.x, " ", non_null.y);
     }
}

void main() {
     foo(Nullable!(inputs_t)()); // prints 0 0
     foo(inputs_t(5, 6).nullable); // prints 5 6
}
```



More information about the Digitalmars-d-learn mailing list