How to make a function that accepts optional struct but can accept struct literal too
russhy
russhy at gmail.com
Sat Oct 16 04:02:09 UTC 2021
On Friday, 15 October 2021 at 21:47:21 UTC, Paul Backus wrote:
> On Friday, 15 October 2021 at 20:33:33 UTC, JN wrote:
>> Is there some nice way of achieving something like this C99
>> code in D?
>>
>> ```c
>> #include <stdio.h>
>>
>> typedef struct {
>> int x, y;
>> } inputs_t;
>>
>> void foo(inputs_t* optional_inputs)
>> {
>> if (!optional_inputs) {
>> printf("0 0\n");
>> } else {
>> printf("%d %d \n", optional_inputs->x,
>> optional_inputs->y);
>> }
>> }
>>
>> int main(void) {
>> foo(NULL); // prints 0 0
>> foo(&(inputs_t){.x = 5, .y = 6}); // prints 5 6
>> }
>> ```
>
> ```d
> static global(alias value) = value;
>
> struct Inputs { int x, y; }
>
> void foo(Inputs* inputs)
> {
> import std.stdio;
> if (inputs is null)
> writeln("0 0");
> else
> writeln(inputs.x, " ", inputs.y);
> }
>
> void main()
> {
> foo(null);
> foo(&global!(Inputs(5, 6)));
> }
> ```
Nice trick, so far Paul's answer is the cleanest, 0 imports,
doesn't change the signature of the method, and he doesn't create
overloading
I remember i was once trying to achieve the same as OP, i ended
up just using a local variable
More information about the Digitalmars-d-learn
mailing list