www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Struct initializers

(This comes after a little chat in #D).
This shows a syntax to initialize structs:

struct S { int x; }
S s1 = {1}; // OK
S[] sa1 = [{2}]; // OK
void main() {
  S s2 = {3}; // OK
  // S[] sa2 = [{4}]; // Error: array initializers as expressions are not

But it's limited, works only for structs in the static data segment.
D has another more flexible syntax for struct initialization, in this case is
for example:

auto s3 = S(5).

I can see few possibilities:
1) All situation can be kept as it is now.
2) The {fields...} syntax to initialize structs can be extended, making it
usable for structs in non static data too (I think this doesn't break the
compatibility with C code because it's just an extension). Such syntax has the
advantage of being a little shorter, because you don't need to repeat the name
of the struct many times, for example when you write an array literal of
3) The {fields...} syntax can be removed, because the Structname() is enough.
This has the advantage of removing a little of complexity from the language,
and frees the {x,y,...} syntax for other purposes, for example to represent a
set literal (as used in Python3 for example). The disadvantage is that C
programmers have to adapt when using D, because a syntax they are used to can't
be used anymore in D. Another small disadvantage is that when porting C code to
D you need to modify a little the syntax of the struct initializers.

I am not sure what I like more. I think the solution 3 looks a little better,
but it has some disadvantages too.

Oct 27 2008