跳轉到內容

D (程式語言)/d2/你好,世界!

50% developed
來自華夏公益教科書,自由的教科書

第 1 課:你好,世界!

[編輯 | 編輯原始碼]

在本課中,您將學習如何使用 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 不同,因為它在末尾添加了一個換行符。
華夏公益教科書