auto ms1 = MyStruct(10, 11);// struct literal,一般简单.
MyStruct ms2 = {10, 11}; // C-style, not preferred
MyStruct ms3 = {b:11, a:10};// Named initializers
立刻初化完:
import std.stdio;
struct Point {
int x, y;
string toString() {
import std.format : format;
return format("(%d, %d)", x, y);
}
}
void main() {
Point[2] ps = [{0,0}, {4,4}];
foreach (p; ps) writeln(p);
}
自定义:
#! /usr/bin/env rdmd
import std.stdio;
struct X {
int a;
this(int x) {
a = x * 2;
}
}
void main() {
auto test = X(22);
writeln(test.a);
}
output: 44
struct Foo {
int x;
this(int a, int b) { x = a + b; }//有它,foo(a)就不行,无它,就可以
}
struct S
{
int x;
}
auto s = S(42);
改成:
struct S
{
int x;
int y;
}
auto s = S(42);
//仍然编译
struct S
{
string s;
int i;
}
auto s = S("hello", 42);
struct S
{
string s;
int foo;
int i;
}
auto s = S("hello", 42);//编译不过
struct S
{
int x;
int y;
}
auto s = S(12, 99);
//构字面量导致漏洞.应声明构造器.
struct S
{
int y;
int x;
}
auto s = S(12, 99);