跳转到内容

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 不同,因为它在末尾添加了一个换行符。
华夏公益教科书