appending newly initialized struct to array
Kenji Hara
k.hara.pg at gmail.com
Tue Apr 17 20:37:02 PDT 2012
On Tuesday, 17 April 2012 at 21:00:55 UTC, simendsjo wrote:
> On Tue, 17 Apr 2012 22:28:31 +0200, maarten van damme
> <maartenvd1994 at gmail.com> wrote:
>
>> Just for fun I decided to complete some codejam challenges in
>> D. At some
>> point I wanted to add structs to an array but I got a compiler
>> error. What
>> am I doing wrong?
>>
>> code:
>> struct test{
>> int x;
>> int y;
>> }
>> void main(){
>> test[] why;
>> why~={3,5};
>> }
>>
>> error:
>> wait.d(7): found '}' when expecting ';' following statement
>> wait.d(8): found 'EOF' when expecting ';' following statement
>> wait.d(8): found 'EOF' when expecting '}' following compound
>> statement
>>
>> Is there any reason a why this wouldn't work?
>
> Sounds like a bug. C style initializers work in other cases:
>
> struct S { int i; }
> void main() {
> S[] arr;
> S s = { 1 };
> arr ~= S(1);
> // But the following barfs
> //arr ~= { 1 };
> //arr ~= { i:1 };
> //arr[0] = { 1 };
> }
No, it is designed. {3,5} is struct initializer:
http://dlang.org/declaration.html#StructInitializer
And it is only allowed in initializer of variable declarations.
> why~={3,5};
This is concat assign expression, so you should use test(3,5)
instead of {3,5}. That is StructLiteral:
http://dlang.org/struct.html#StructLiteral
and it is an expression.
Bye.
Kenji Hara
More information about the Digitalmars-d-learn
mailing list