Thread overview | |||||
---|---|---|---|---|---|
|
December 12, 2018 how to initialize nested struct elegantly? | ||||
---|---|---|---|---|
| ||||
import std.stdio; struct AA { int i; char c; double d; string s; float f; } struct BB { float f; AA[2] a; } void print(BB* bb) { writefln("bb.a[0].i=%d bb.f=%f", bb.a[0].i, bb.f); } void main() { //dlang AA aa = { i:1010, f:0.1f }; BB bb = { f : 0.2f, a : [ AA(1010, 0,0,null,0.1f), AA(1020,0,0,null,0.2f) ] }; print(&bb); /************************************************/ /* //C99 print( &(BB){ .f = 0.2f, .a = { [0] = { .i = 1010, .f = 0.1f } [1] = { .i = 1020, .f = 0.2f } } }); */ } dlang version has two unnecessary symbols aa and bb, which is ugly compare to c99 one. |
December 12, 2018 Re: how to initialize nested struct elegantly? | ||||
---|---|---|---|---|
| ||||
Posted in reply to elvisxzhou | On Wednesday, 12 December 2018 at 09:49:58 UTC, elvisxzhou wrote:
> import std.stdio;
>
> struct AA
> {
> int i;
> char c;
> double d;
> string s;
> float f;
> }
>
> struct BB
> {
> float f;
> AA[2] a;
> }
>
> void print(BB* bb)
> {
> writefln("bb.a[0].i=%d bb.f=%f", bb.a[0].i, bb.f);
> }
>
> void main()
> {
> //dlang
> AA aa = {
> i:1010,
> f:0.1f
> };
>
> BB bb = {
> f : 0.2f,
> a : [
> AA(1010, 0,0,null,0.1f),
> AA(1020,0,0,null,0.2f)
> ]
> };
>
> print(&bb);
>
> /************************************************/
> /*
>
> //C99
> print( &(BB){
> .f = 0.2f,
> .a = {
> [0] = { .i = 1010, .f = 0.1f }
> [1] = { .i = 1020, .f = 0.2f }
> }
> });
>
> */
> }
>
>
> dlang version has two unnecessary symbols aa and bb, which is ugly compare to c99 one.
aa is already eliminated in the example, but you know where the ugly is.
|
December 12, 2018 Re: how to initialize nested struct elegantly? | ||||
---|---|---|---|---|
| ||||
Posted in reply to elvisxzhou | On 12/12/18 4:49 AM, elvisxzhou wrote:
> dlang version has two unnecessary symbols aa and bb, which is ugly compare to c99 one.
>
Well, this works:
BB bb = {
f : 0.2f,
a : [
{i:1010, f:0.1f}, // note the nested field name syntax
{i:1020, f:0.2f}
]
};
writeln(bb);
But you can't use that syntax for expressions, only for initialization.
So, no you can't get rid of the bb if you want to use that syntax.
Or you can just create a factory function to do what you want.
-Steve
|
Copyright © 1999-2021 by the D Language Foundation