跳至內容

D(程式語言)/d2/Hello, World!

50% developed
來自華夏公益教科書,開放的書籍,開放的世界

第一課:Hello, World!

[編輯 | 編輯原始碼]

在本課中,您將學習如何使用 Phobos 庫寫入控制檯。此外,您還將瞭解 D 程式的結構。

入門程式碼

[編輯 | 編輯原始碼]

我們將從絕對必要的 Hello World 示例開始。

Hello World

[編輯 | 編輯原始碼]
/* This program prints a
   hello world message
   to the console.  */

import std.stdio;

void main()
{
    writeln("Hello, World!");
}

在本課中,我們將看到 import 語句、主函式、Phobos 標準庫的使用,以及一個程式碼註釋

import std.stdio

[編輯 | 編輯原始碼]

Phobos 庫包含 std.stdio 模組,該模組又包含 writeln 函式(以及其他各種函式)。要使用該函式,您必須先匯入該模組。請注意,D 中的語句以分號結尾。

void main()

[編輯 | 編輯原始碼]

所有可執行的 D 程式都包含一個主函式。此函式不返回值,因此它被宣告為“void”(從技術上講,這是一個過度簡化。main 的返回值將在後面更詳細地解釋。)此函式在程式執行時執行。

函式體程式碼包含在花括號中。雖然縮排和空格只針對讀者,而不是針對編譯器,但請確保您正確且一致地縮排和格式化程式碼;這通常是一種良好的編碼實踐。

writeln 和 write 系列

[編輯 | 編輯原始碼]

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:
*/
  • writelnwrite 不同,因為它在末尾添加了一個換行符。
華夏公益教科書