我們經(jīng)常使用可變的變量,但是在很多情況下不需要可變性。
D的不變性概念由const和immutable關(guān)鍵字表示,盡管這兩個(gè)詞本身的含義很接近,但它們?cè)诔绦蛑械穆氊?zé)有所不同,有時(shí)是不兼容的。
枚舉常量使將常量值與有意義的名稱相關(guān)聯(lián)成為可能,一個(gè)簡(jiǎn)單的如下所示。
import std.stdio;
enum Day{
Sunday=1,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday
}
void main() {
Day day;
day=Day.Sunday;
if (day == Day.Sunday) {
writeln("The day is Sunday");
}
}
編譯并執(zhí)行上述代碼后,將產(chǎn)生以下輸出-
The day is Sunday
不變變量可以在程序執(zhí)行期間確定,它只是指示編譯器在初始化之后變得不可變。一個(gè)簡(jiǎn)單的如下所示。
import std.stdio;
import std.random;
void main() {
int min=1;
int max=10;
immutable number=uniform(min, max + 1);
//cannot modify immutable expression number
//number=34;
typeof(number) value=100;
writeln(typeof(number).stringof, number);
writeln(typeof(value).stringof, value);
}
編譯并執(zhí)行上述代碼后,將產(chǎn)生以下輸出-
immutable(int)4
immutable(int)100
您可以在上面的示例中看到如何在打印時(shí)將數(shù)據(jù)類型傳輸?shù)搅硪粋€(gè)變量并使用stringof。
常量變量不能像不可變一樣進(jìn)行修改,不變變量可以作為不變參數(shù)傳遞給函數(shù),因此建議在const上使用不變。
import std.stdio;
import std.random;
void main() {
int min=1;
int max=10;
const number=uniform(min, max + 1);
//cannot modify const expression number|
//number=34;
typeof(number) value=100;
writeln(typeof(number).stringof, number);
writeln(typeof(value).stringof, value);
}
如果我們編譯并運(yùn)行以上代碼,這將產(chǎn)生以下輸出-
const(int)7
const(int)100
const會(huì)刪除有關(guān)原始變量是可變變量還是不可變變量的信息,因此使用不可變變量會(huì)使它傳遞保留原始類型的其他
import std.stdio;
void print(immutable int[] array) {
foreach (i, element; array) {
writefln("%s: %s", i, element);
}
}
void main() {
immutable int[] array=[ 1, 2 ];
print(array);
}
編譯并執(zhí)行上述代碼后,將產(chǎn)生以下輸出-
0: 1
1: 2
更多建議: