www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Struct initialization using member syntax without variable

reply Jacob Carlborg <doob me.com> writes:
To initialize a struct with the member names a variable is required. 
Example:

struct Foo
{
     int a;
     int b;
}

Foo foo = { a: 3, b: 4 };

That's a bit annoying when you want to pass the struct to a function or 
return it.

Foo bar()
{
     return { a: 3, b: 4 }; // error
}

void bar(Foo foo);

bar({ a: 3, b: 4 }); // error

Is there any reason for this limitation? I guess it will make function 
overloading more difficult, but that could easily be solved with the 
following syntax:

bar(Foo{ a: 3, b: 4 });

Or this:

bar(Foo(a: 3, b: 4));

This would also allow one to use "auto" when declaring a variable:

auto foo = Foo{ a: 3, b: 4 };

-- 
/Jacob Carlborg
Jan 14 2016
parent reply w0rp <devw0rp gmail.com> writes:
Maybe there is some parsing difficulty, but if it's possible to 
add something like this, I think it would be nice.
Jan 14 2016
parent Jacob Carlborg <doob me.com> writes:
On 2016-01-14 13:22, w0rp wrote:
 Maybe there is some parsing difficulty, but if it's possible to add
 something like this, I think it would be nice.
I hardly doubt it. -- /Jacob Carlborg
Jan 14 2016