Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help


x-i18n: generated_at: “2026-03-01T09:20:21Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 645189892417cf5431fafb29c4e9b413db2c8cb07fb99e993efaf3c3e9d7a143 source_path: ch01-02-hello-world.md workflow: 16

你好,世界! (Hello, World!)

Hello, World!

现在你已经安装了 Rust,是时候编写你的第一个 Rust 程序了。学习一门新语言时,编写一个在屏幕上打印 Hello, world! 文本的小程序是一个传统,所以我们在这里也这样做!

Now that you’ve installed Rust, it’s time to write your first Rust program. It’s traditional when learning a new language to write a little program that prints the text Hello, world! to the screen, so we’ll do the same here!

注意:本书假设你对命令行有基本的了解。Rust 对你的编辑器、工具或代码存放位置没有特殊要求,所以如果你更喜欢使用 IDE 而不是命令行,请随意使用你喜欢的 IDE。现在许多 IDE 都有一定程度的 Rust 支持;详情请查看 IDE 的文档。Rust 团队一直致力于通过 rust-analyzer 提供出色的 IDE 支持。更多详情请参见附录 D

Note: This book assumes basic familiarity with the command line. Rust makes no specific demands about your editing or tooling or where your code lives, so if you prefer to use an IDE instead of the command line, feel free to use your favorite IDE. Many IDEs now have some degree of Rust support; check the IDE’s documentation for details. The Rust team has been focusing on enabling great IDE support via rust-analyzer. See Appendix D for more details.

项目目录设置 (Project Directory Setup)

Project Directory Setup

首先,你要创建一个目录来存储你的 Rust 代码。Rust 并不关心你的代码存放在哪里,但对于本书中的练习和项目,我们建议在你的主目录中创建一个 projects 目录,并将所有项目都存放在那里。

You’ll start by making a directory to store your Rust code. It doesn’t matter to Rust where your code lives, but for the exercises and projects in this book, we suggest making a projects directory in your home directory and keeping all your projects there.

打开终端并输入以下命令,在 projects 目录中创建一个 projects 目录和一个用于“Hello, world!”项目的目录。

Open a terminal and enter the following commands to make a projects directory and a directory for the “Hello, world!” project within the projects directory.

对于 Linux、macOS 和 Windows 上的 PowerShell,请输入:

For Linux, macOS, and PowerShell on Windows, enter this:

$ mkdir ~/projects
$ cd ~/projects
$ mkdir hello_world
$ cd hello_world

对于 Windows CMD,请输入:

For Windows CMD, enter this:

> mkdir "%USERPROFILE%\projects"
> cd /d "%USERPROFILE%\projects"
> mkdir hello_world
> cd hello_world

Rust 程序基础 (Rust Program Basics)

Rust Program Basics

接下来,创建一个新的源文件并将其命名为 main.rs。Rust 文件总是以 .rs 扩展名结尾。如果你的文件名中使用了多个单词,惯例是使用下划线来分隔它们。例如,使用 hello_world.rs 而不是 helloworld.rs

Next, make a new source file and call it main.rs. Rust files always end with the .rs extension. If you’re using more than one word in your filename, the convention is to use an underscore to separate them. For example, use hello_world.rs rather than helloworld.rs.

现在打开你刚刚创建的 main.rs 文件,并输入示例 1-1 中的代码。

Now open the main.rs file you just created and enter the code in Listing 1-1.

fn main() {
    println!("Hello, world!");
}

保存文件并回到 ~/projects/hello_world 目录下的终端窗口。在 Linux 或 macOS 上,输入以下命令来编译并运行该文件:

Save the file and go back to your terminal window in the ~/projects/hello_world directory. On Linux or macOS, enter the following commands to compile and run the file:

$ rustc main.rs
$ ./main
Hello, world!

在 Windows 上,输入命令 .\main 而不是 ./main

On Windows, enter the command .\main instead of ./main:

> rustc main.rs
> .\main
Hello, world!

无论你使用的是什么操作系统,字符串 Hello, world! 都应该打印到终端。如果你没有看到这个输出,请参阅安装章节的 “故障排除” 部分以寻求帮助。

Regardless of your operating system, the string Hello, world! should print to the terminal. If you don’t see this output, refer back to the “Troubleshooting” part of the Installation section for ways to get help.

如果 Hello, world! 确实打印出来了,恭喜你!你正式编写了一个 Rust 程序。这让你成为了一名 Rust 程序员——欢迎加入!

If Hello, world! did print, congratulations! You’ve officially written a Rust program. That makes you a Rust programmer—welcome!

Rust 程序的解剖 (The Anatomy of a Rust Program)

The Anatomy of a Rust Program

让我们详细回顾一下这个 “Hello, world!” 程序。这是拼图的第一块:

Let’s review this “Hello, world!” program in detail. Here’s the first piece of the puzzle:

fn main() {

}

这些行定义了一个名为 main 的函数。main 函数是特殊的:它是每个可执行 Rust 程序中首先运行的代码。在这里,第一行声明了一个名为 main 的函数,它没有参数且不返回任何内容。如果有参数,它们会放在圆括号 (()) 内。

These lines define a function named main. The main function is special: It is always the first code that runs in every executable Rust program. Here, the first line declares a function named main that has no parameters and returns nothing. If there were parameters, they would go inside the parentheses (()).

函数体包裹在 {} 中。Rust 要求所有函数体都要用花括号括起来。良好的风格是将左花括号与函数声明放在同一行,并在两者之间添加一个空格。

The function body is wrapped in {}. Rust requires curly brackets around all function bodies. It’s good style to place the opening curly bracket on the same line as the function declaration, adding one space in between.

注意:如果你想在所有 Rust 项目中坚持统一的标准风格,可以使用名为 rustfmt 的自动格式化工具将代码格式化为特定的风格(有关 rustfmt 的更多信息请参见附录 D)。Rust 团队已将此工具与标准 Rust 发行版(如 rustc)一并提供,因此它应该已经安装在你的电脑上了!

Note: If you want to stick to a standard style across Rust projects, you can use an automatic formatter tool called rustfmt to format your code in a particular style (more on rustfmt in Appendix D). The Rust team has included this tool with the standard Rust distribution, as rustc is, so it should already be installed on your computer!

main 函数的函数体包含以下代码:

The body of the main function holds the following code:

#![allow(unused)]
fn main() {
println!("Hello, world!");
}

这一行完成了这个小程序中的所有工作:它将文本打印到屏幕上。这里有三个重要的细节需要注意。

This line does all the work in this little program: It prints text to the screen. There are three important details to notice here.

首先,println! 调用了一个 Rust 宏 (macro)。如果它调用的是一个函数,它将被输入为 println(没有 !)。Rust 宏是一种编写代码的方法,它通过生成代码来扩展 Rust 语法,我们将在 第 20 章 中更详细地讨论它们。现在,你只需要知道使用 ! 意味着你正在调用一个宏而不是一个普通的函数,并且宏并不总是遵循与函数相同的规则。

First, println! calls a Rust macro. If it had called a function instead, it would be entered as println (without the !). Rust macros are a way to write code that generates code to extend Rust syntax, and we’ll discuss them in more detail in Chapter 20. For now, you just need to know that using a ! means that you’re calling a macro instead of a normal function and that macros don’t always follow the same rules as functions.

其次,你看到了 "Hello, world!" 字符串。我们将这个字符串作为参数传递给 println!,然后该字符串被打印到屏幕上。

Second, you see the "Hello, world!" string. We pass this string as an argument to println!, and the string is printed to the screen.

第三,我们以分号 (;) 结尾,这表示该表达式已经结束,下一个表达式准备开始。大多数 Rust 代码行都以分号结尾。

Third, we end the line with a semicolon (;), which indicates that this expression is over, and the next one is ready to begin. Most lines of Rust code end with a semicolon.

编译与运行是分开的步骤 (Compilation and Execution)

Compilation and Execution

你刚刚运行了一个新创建的程序,所以让我们检查一下这个过程中的每个步骤。

You’ve just run a newly created program, so let’s examine each step in the process.

在运行 Rust 程序之前,必须使用 Rust 编译器对其进行编译,方法是输入 rustc 命令并传递源文件的名称,如下所示:

Before running a Rust program, you must compile it using the Rust compiler by entering the rustc command and passing it the name of your source file, like this:

$ rustc main.rs

如果你有 C 或 C++ 背景,你会注意到这与 gccclang 类似。成功编译后,Rust 会输出一个二进制可执行文件。

If you have a C or C++ background, you’ll notice that this is similar to gcc or clang. After compiling successfully, Rust outputs a binary executable.

在 Linux、macOS 和 Windows 上的 PowerShell 上,你可以通过在 Shell 中输入 ls 命令来查看该可执行文件:

On Linux, macOS, and PowerShell on Windows, you can see the executable by entering the ls command in your shell:

$ ls
main  main.rs

在 Linux 和 macOS 上,你会看到两个文件。在 Windows 的 PowerShell 上,你会看到与使用 CMD 相同的三个文件。在 Windows 的 CMD 上,你会输入以下内容:

On Linux and macOS, you’ll see two files. With PowerShell on Windows, you’ll see the same three files that you would see using CMD. With CMD on Windows, you would enter the following:

> dir /B %= the /B option says to only show the file names =%
main.exe
main.pdb
main.rs

这显示了带有 .rs 扩展名的源代码文件、可执行文件(在 Windows 上是 main.exe,但在所有其他平台上是 main),以及在使用 Windows 时,包含调试信息且扩展名为 .pdb 的文件。从这里,你可以像这样运行 mainmain.exe 文件:

This shows the source code file with the .rs extension, the executable file (main.exe on Windows, but main on all other platforms), and, when using Windows, a file containing debugging information with the .pdb extension. From here, you run the main or main.exe file, like this:

$ ./main # or .\main on Windows

如果你的 main.rs 是你的 “Hello, world!” 程序,这一行将在你的终端上打印 Hello, world!

If your main.rs is your “Hello, world!” program, this line prints Hello, world! to your terminal.

如果你更熟悉 Ruby、Python 或 JavaScript 等动态语言,你可能不习惯将编译和运行程序作为分开的步骤。Rust 是一种预先编译 (ahead-of-time compiled) 的语言,这意味着你可以编译一个程序并将可执行文件交给其他人,即使他们没有安装 Rust 也可以运行它。如果你给别人一个 .rb.py.js 文件,他们需要分别安装 Ruby、Python 或 JavaScript 的实现。但在那些语言中,你只需要一个命令即可编译并运行你的程序。在语言设计中,一切都是一种权衡。

If you’re more familiar with a dynamic language, such as Ruby, Python, or JavaScript, you might not be used to compiling and running a program as separate steps. Rust is an ahead-of-time compiled language, meaning you can compile a program and give the executable to someone else, and they can run it even without having Rust installed. If you give someone a .rb, .py, or .js file, they need to have a Ruby, Python, or JavaScript implementation installed (respectively). But in those languages, you only need one command to compile and run your program. Everything is a trade-off in language design.

对于简单的程序,仅使用 rustc 编译就可以了,但随着项目的增长,你会希望管理所有选项并让共享代码变得容易。接下来,我们将向你介绍 Cargo 工具,它将帮助你编写现实世界的 Rust 程序。

Just compiling with rustc is fine for simple programs, but as your project grows, you’ll want to manage all the options and make it easy to share your code. Next, we’ll introduce you to the Cargo tool, which will help you write real-world Rust programs.