struct initialization and assignment by field name
Bobby Bingham
uhmmmm at gmail.com
Sat Dec 1 11:22:39 PST 2012
I'm just starting out with D, and am wondering about some differences
with C regarding struct literals. In C99, I can do this:
struct MyStruct {
int number;
char letter;
};
int main() {
static struct MyStruct foo = { .number = 42, .letter = 'a' };
struct MyStruct bar = { .number = 42, .letter = 'a' };
bar = (struct MyStruct) { .number = 42, .letter = 'a' };
return 0;
}
That is, I can initialize static and non-static struct variables by
specifying the fields as key-value pairs. I can also assign a struct
literal to an already-declared struct variable in the same way.
If we try this in D:
struct MyStruct {
int number;
char letter;
}
int main() {
static MyStruct foo = { number:42, letter:'a' }; // works
MyStruct bar = { number:42, letter:'a' }; // works despite [1]
bar = { number:42, letter:'a' }; // fails to compile
return 0;
}
That is, I can do something similar for static struct initializers in D,
and non-static struct initializers despite this being documented as not
allowed.
It appears that this form of struct literal really can only be used in
initializers -- the assignment to a previously declared varaible fails to
compile.
I'm hoping somebody can shed some light on the rationale for only
supporting this form of struct literal in initializers. And also why it's
documented to only work for static initializers -- is this an error in
the documentation, or is the compiler allowing things it shouldn't?
Thanks,
Bobby
1. http://dlang.org/struct.html
"The static initializer syntax can also be used to initialize non-
static variables, provided that the member names are not given."
More information about the Digitalmars-d-learn
mailing list