C++ allows you to define named instances of anonymous structs and classes:
struct Container {
struct {
int x;
int y;
} point;
void print() const {
std::cout << "Point: (" << point.x << ", " << point.y << ")\n";
}
};
int main() {
Container c;
c.point.x = 10;
c.point.y = 20;
c.print();
}
In D, the only way to approximate this is to define a type and then instantiate an instance of it within the struct/class:
struct Container {
struct Point {
int x;
int y;
}
Point point;
}
This approximation is superfluous; why specify a type that is never meant to be used by users? When nested data structures become larger and larger, this type of declare-and-instantiate pattern becomes an annoyance to write, and hard to read (as the type is separated from the declaration).
Named instances of anonymous structs allow for less complexity, less verbosity, and less ambiguity over intent. The information about the variable is right next to the instantiation, and the code clearly communicates that point is simply a nested group within container, not an individual type that can/should be used on its own.
Since structs don't end with semicolons in D, a different syntax must be used. I believe that prefixing the struct with the inline
keyword is the best fit:
struct Container {
inline struct point {
int x;
int y;
}
}
This doesn't add any extra keywords, and I believe it makes it clean that the struct is a single instance that is declared in the enclosing scope.