Initializing variables

From D Wiki
Revision as of 17:50, 14 December 2012 by Quickfur (talk | contribs) (stub)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

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

int x = 10;

declares an int variable named x, 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 constant 10 is, by default, an int.

Structs

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");

Classes

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);