Difference between revisions of "Initializing variables"
(Added category) |
(→Introduction: constant -> decimal integer literal) |
||
Line 5: | Line 5: | ||
int x = 10; | int x = 10; | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | declares | + | 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: | + | However, because D has ''static type inference'', there is often no need to explicitly specify the type of the variable: |
<syntaxhighlight lang=D> | <syntaxhighlight lang=D> | ||
auto x = 10; | auto x = 10; | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | declares an int variable named | + | 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. |
==Structs== | ==Structs== |
Revision as of 06:14, 10 February 2018
Introduction
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.
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);
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)