Difference between revisions of "Initializing variables"

From D Wiki
Jump to: navigation, search
(stub)
 
(const, immutable, etc)
Line 50: Line 50:
 
<syntaxhighlight lang=D>
 
<syntaxhighlight lang=D>
 
auto mc = new MyClass(123);
 
auto mc = new MyClass(123);
 +
</syntaxhighlight>
 +
 +
==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:
 +
 +
<syntaxhighlight lang=D>
 +
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)
 
</syntaxhighlight>
 
</syntaxhighlight>

Revision as of 17:55, 14 December 2012

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

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)