D(程式語言)/d2/型別和宣告
外觀
< D(程式語言)
(從 D(程式語言)/d2/第 2 課 重定向)在本課中,您將學習如何宣告和使用變數。
import std.stdio;
int b;
void main()
{
b = 10;
writeln(b); // prints 10
int c = 11;
// int c = 12; Error: declaration c is already defined
string a = "this is a string";
writeln(a); // prints this is a string
// a = 1; Error, you can't assign an int to a string variable
int d, e, f; // declaring multiple variables is allowed
}
import std.stdio;
void main()
{
int hot_dogs = 10;
int burgers = 20;
auto total = hot_dogs + burgers;
string text = burgers + " burgers"; // Error! Incompatible types int and string
writeln(hot_dogs, " hot dogs and ", burgers, " burgers");
writeln(total, " total items");
}
在本課中,我們看到了變數的宣告和賦值。
宣告變數的語法是
type identifier;
您也可以在同一時間分配一個值。
type identifier = value;
D 允許您在同一行中宣告多個相同型別的變數。如果您寫
int i, j, k = 30;
i、j 和 k 都被宣告為 int,但只有 k 被賦值為 30。它與以下程式碼相同
int i, j;
int k = 30;
如果宣告以 auto 開頭,則編譯器將自動推斷宣告變數的型別。事實上,它不必是 auto。任何儲存類都可以使用。儲存類是 D 中內建的構造,例如 auto 或 immutable。此程式碼聲明瞭一個不可變的變數 a,其值為 3。編譯器會確定其型別為 int。
immutable a = 3;
您將在後面學習更多關於儲存類的知識。
writeln 是一個非常有用的函式,用於寫入 stdout。writeln 的一個特殊之處在於:它可以接受任何型別的變數。它還可以接受無限數量的引數。例如
writeln("I ate ", 5, " hot dogs and ", 2, " burgers.");
// prints I ate 5 hot dogs and 2 burgers.
別擔心,writeln 並沒有什麼神奇之處。write 家族中的所有函式都是使用 100% 有效的 D 程式碼在 stdio.d 中實現的,stdio.d 位於 Phobos 標準庫中。
- 類似這樣的語法:
int i, j, k = 1, 2, 3;是不允許的。 - 類似這樣的語法:
int, string i, k;也是不允許的。 auto不是一個型別。您不能這樣做:auto i;因為編譯器無法推斷 i 的型別。auto僅僅是一個儲存類,它告訴編譯器從您在同一行中為其分配的值中推斷出型別。