D (程式語言)/d2/型別,續
外觀
< D (程式語言)
(從 D (程式語言)/d2/第 4 課 重定向)在本課中,您將看到所有其他型別。其中許多型別您會很熟悉,但請注意,C 和 D 在其內建型別中存在很多差異。
import std.stdio;
void main()
{
bool a; // default initialized to false
a = 1;
a = false;
uint aa = 53; //unsigned int
ulong bb = 10395632; //unsigned long
short cc = 100;
ushort dd = cc; //dd == 100
byte b = 0x5E;
writeln(b); // prints 94
b = 110;
ubyte c = 255; //maximum value for a ubyte
assert(c == ubyte.max);
short d = 50;
long e = d;
writeln(e); // 50
float f; // default initialized to float.nan
float g = 3.13;
double h = g * 2.5;
// largest hardware implemented floating-point
real i = 373737373737377373.0;
writeln(i); // 3.73737e+17
// these numbers are not real:
idouble j; //default = double.nan * 1.0i
ifloat k;
ireal l;
cfloat m = 5 + 32.325i; // a complex number
// unsigned 8-bit UTF-8
char n; // default initialized to 0xFF
n = 'm';
writeln(n); // m
// unsigned 16-bit UTF-16
wchar o; // default = 0xFFFF
// unsigned 32-bit UTF-32
dchar p; // default = 0x0000FFFF
}
使用 assert 允許您檢查某個表示式是否為真。== 表示等於(不要與 = 混淆,= 用於賦值變數)。檢查在執行時進行,如果括號內的任何內容計算結果為假,則會發生斷言錯誤,並且程式將終止。
void main()
{
bool a = true;
assert(a);
assert(2346924); // anything that's not 0 or false
// assert(false); Assertion failure
int i = 4628;
assert(i == 4628); // (i == 4628) evaluates to true
assert(i != 4528); // (i != 4528) evaluates to true
assert(i >= 0); // yes, i is greater or equal to 0
}
型別具有預設初始化器。這意味著,如果它們被宣告但沒有被分配任何值,它們預設將等於某些東西。
int i; //i = int.init
assert(int.init == 0); // i is definitely 0
float b = float.init; //b = float.nan
可以從任何型別或物件查詢屬性。當查詢型別或物件的屬性時,屬性名稱和識別符號之間有一個點。
type.property
任何型別的 init 屬性包含預設情況下初始化此型別物件的 value。對於數字型別,您可以使用其各自的屬性找到最小值和最大值:type.min 和 type.max。您還可以找到型別在記憶體中的大小:type.sizeof。如果您想要宣告但不想初始化某些東西,您可以執行此操作
int i = void;
然後,i 未初始化;它的值是未定義的垃圾。
D 允許您以幾種有用的基數和形式編寫數字。因此,如果您想將 A4 的十六進位制數加到一百萬三千一百三十七千六百三十七和 1011010101 的二進位制數,您可以編寫以下內容
import std.stdio;
void main()
{
writeln(0xA4 + 1_113_637 + 0b10_11_010101);
// hex numbers are prefixed by 0x
// binary numbers by 0b
// the answer is 1114526
}
請注意,數字中間的下劃線會被完全忽略。它們是 100% 可選的,並且對於格式化長數字很有用。
- 您可以檢視 此參考 以獲取有關 D 的詞法語法的更多資訊。很快就會有一課寫出有關此主題的最新資訊。