Initializing variables

From D Wiki
Jump to: navigation, search


D inherits from C and C++ in its basic style of variable initialization. For example:

int x = 10;

declares a variable named x of type int, whose initial value is 10.

However, because D has static type inference, there is often no need to explicitly specify the type of the variable:

auto x = 10;

declares an int variable named x, whose initial value is 10. The type of x is automatically deduced to be int, because the decimal integer literal 10 has a type of int.

Variables can also be declared without initialization.[1]

int x = void;


Structs are initialized using a constructor-like syntax:

struct MyStruct
    int x;
    string z;

MyStruct ms = MyStruct(10, "abc");

However, since the constructor-like syntax already specifies what the type of ms will be, it does not need to be repeated:

auto ms = MyStruct(10, "abc");


Class objects are initialized with the new keyword:

class MyClass
    int x;
    this(int _x) { this.x = _x; }
MyClass mc = new MyClass(123);

Again, static type inference allows us to only name the class once:

auto mc = new MyClass(123);

This is helpful especially when the class name is long:

class ThisIsAClassWithAVeryLongName { ... }

// This is a lot of unnecessary typing to do:
ThisIsAClassWithAVeryLongName mc = new ThisIsAClassWithAVeryLongName();

// This is much better:
auto mc = new ThisIsAClassWithAVeryLongName();

Const, immutable, etc.

The auto keyword actually does not mean "automatically infer the type"; it actually means "automatic variable", as in, not a class member but a variable allocated in its scope. When coupled with static type inference, it serves as a convenient placeholder for the omitted type name.

So, declaring a const int or immutable variable can be written this way:

const x = 10;      // the type of x is const(int)
immutable y = 20;  // the type of y is immutable(int)

const ms = MyStruct(123, "def"); // the type of ms is const(MyStruct)
const mc = new MyClass(321);     // the type of mc is immutable(MyClass)

See also

  • 6. Declarations: Void Initialization