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

你好,世界!

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

首先,你要创建一个用于存放 Rust 代码的目录。Rust 并不关心你的代码存放在哪里,但对于本书中的练习和项目,我们建议在你的家目录(home directory)下创建一个 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

接下来,创建一个新的源文件并将其命名为 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

让我们详细回顾一下这个 “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

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

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 %= /B 选项表示仅显示文件名 =%
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 # 或者在 Windows 上使用 .\main

如果你的 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.