D(程式語言)/d2/你好,世界!
外觀
< D(程式語言)
(重定向自 D(程式語言)/d2/第一課)在本課中,您將學習如何使用 Phobos 庫向控制檯寫入內容。您還將瞭解 D 程式的結構。
我們將從絕對必要的 Hello World 示例開始。
/* This program prints a
hello world message
to the console. */
import std.stdio;
void main()
{
writeln("Hello, World!");
}
在本課中,我們看到了 import 語句、主函式、Phobos 標準庫的使用,以及程式碼註釋。
Phobos 庫包含 std.stdio 模組,該模組包含 writeln 函式(以及其他各種函式)。要使用該函式,您必須首先匯入該模組。請注意,D 中的語句以分號結尾。
所有可執行的 D 程式都包含一個 main 函式。該函式不返回值,因此被宣告為“void”(從技術上講,這是一種過於簡化的說法。main 的返回值將在後面的課程中詳細講解。)該函式在程式執行時被執行。
函式體程式碼用大括號括起來。雖然縮排和空格僅供讀者參考,而不是供編譯器參考,但請確保您的程式碼縮排和格式正確且一致;這通常是一個良好的編碼習慣。
writeln 用於寫入標準輸出(在本例中為控制檯)。您可以提供一個字串,例如 "Hello, World!" 作為引數,該字串將被打印出來。該函式有四種基本形式:帶或不帶格式化,以及帶或不帶尾隨換行符。為了演示它們的工作方式,以下所有程式碼都是等效的(儘管第一個和第三個程式碼在 Windows 上不會重新整理 stdout)
// write: Plain vanilla
write("Hello, World!\n"); // The \n is a newline
write("Hello, ", "World!", "\n");
write("Hello, ");
write("World!");
write("\n");
// writeln: With automatic newline
writeln("Hello, World!");
writeln("Hello, ", "World!");
// writef: Formatted output
writef("Hello, %s!\n", "World");
// writefln: Formatted output with automatic newline
writefln("Hello, %s!", "World");
writefln("%s, %s!", "Hello", "World");
writefln("%2$s, %1$s!", "World", "Hello"); // Backwards order
該程式的前幾行是註釋。它們被編譯器忽略。塊註釋用 /* */ 括起來。行註釋在 // 後面繼續。
這是一個行註釋示例
import std.stdio; // I am a comment
void main(){} //this program does nothing
D 還支援巢狀塊註釋,用 /+ +/ 括起來
/+
thisIsCommentedOut();
/+ thisIsCommentedOut(); +/
thisIsSTILLCommentedOut();
+/
這與普通塊註釋不同,普通塊註釋的行為與 C 中一樣
/*
thisIsCommentedOut();
/* thisIsCommentedOut(); */
thisIsNOTCommentedOut();
// The following line is a syntax error:
*/
writeln與write不同,因為它在末尾添加了一個換行符。