Whats going on with this?

claptrap clap at trap.com
Fri Oct 2 23:28:04 UTC 2020

import std;

import std.stdio;

struct Foo
     int a = 0, b = 0;

     this(int[2] vars)
         this.a = vars[0];
         this.b = vars[1];
     //    writeln("constructor called");


Foo foo = [300,300];

void main()

Compiles and works OK. I cant see anything in the struct docs 
explaining why that array on the right hand side is automatically 
converted to a constructor call.

Weird thing is if you un-comment the writeln in the constructor 
it wont compile. You get this...

/dlang/dmd/linux/bin64/../../src/phobos/std/stdio.d(4839): Error: 
variable impl cannot be modified at compile time
called from here: makeGlobal()
called from here: trustedStdout()
onlineapp.d(13):        called from here: writeln("constructor 
onlineapp.d(18):        called from here: Foo(0, 0).this([300, 

How ever if you move Point foo declaration into the main function 
it works OK.

What exactly is going on? I mean it looks like the Foo is default 
constructed and then constructed on top with a call to the arary 
constructor? But why?

Why would putting in the writeln cause it to fail? Is it maybe 
trying to create the foo at compile time?

More information about the Digitalmars-d-learn mailing list