Can now use alias for collapsing multiple fields in nested structs

Derek Fawcus dfawcus+dlang at employees.org
Thu Jan 2 19:58:47 UTC 2025


On Thursday, 2 January 2025 at 19:08:06 UTC, Walter Bright wrote:
> On 1/2/2025 6:32 AM, Derek Fawcus wrote:
>> The closest native equivalent in D, would seem to be the 
>> following, making use of the new facility.
>> 
>> ```D
>> struct outer {
>>      int a;
>>      struct inner_ {
>>              int b;
>>              int c;
>>      }
>>      inner_ inner;
>>      int d;
>>      alias b = inner.b;
>>      alias c = inner.c;
>> };
>> ```
>> 
>> Or is there a nicer way to write that in D?
>
> ```
> struct outer {
>     int a;
>     struct {
>         int b;
>         int c;
>     }
>     int d;
> }
> ```

That does not yield the ability to reference the inner part as an 
entity/group.  Whereas that is possible with the D struct I 
proposed.

e.g. using the prior C definition, I can reference it from C as:

```C
#include <stdio.h>

#include "group.c"

void main() {
	struct outer o;

	o.a = 1; o.b = 2; o.c = 3; o.d = 4;
	printf("inner b = %d, inner c = %d\n", o.inner.b, o.inner.c);
	printf("sizeof outer = %lu, sizeof inner = %lu\n", sizeof o, 
sizeof o.inner);
}
```

or from D as:

```D
import core.stdc.stdio;

import group;

void main() {
	outer o;

	o.a = 1; o.b = 2; o.c = 3; o.d = 4;
	printf("inner b = %d, inner c = %d\n", o.inner.b, o.inner.c);
	printf("sizeof outer = %lu, sizeof inner = %lu\n", o.sizeof, 
o.inner.sizeof);
}
```

Or more likely, passing the address of o.inner to some other 
function.


More information about the Digitalmars-d mailing list