Rust入门:从环境搭建到第一个程序 | Getting Started with Rust: Setup and First Program
第 1 章:Rust入门:从环境搭建到第一个程序 | Getting Started with Rust: Setup and First Program
1.1 开启Rust之旅 | Beginning the Rust Journey
在浩瀚的编程语言宇宙中,每一门语言都有其独特的定位与使命。有的语言追求极致的执行效率,有的语言注重开发的便捷性,还有的语言致力于提供强大的抽象能力。而Rust,这门由Mozilla研究院于2010年首次公开发布的系统级编程语言,选择了一条与众不同的道路——在不牺牲性能的前提下,通过编译器的严格检查来消除内存安全问题,同时保留零成本抽象的能力。
> In the vast universe of programming languages, each language has its unique positioning and mission. Some languages pursue extreme execution efficiency, others focus on development convenience, and still others are dedicated to providing powerful abstraction capabilities. Rust, a systems programming language first publicly released by Mozilla Research in 2010, chose a different path—eliminating memory safety problems through the compiler's strict checking without sacrificing performance, while retaining the ability of zero-cost abstraction.
Rust的设计理念可以概括为三个核心原则:安全(Safety)、并发(Concurrency)、实用(Practicality)。这三个原则并非孤立存在,而是相互交织、互为支撑。安全是Rust最显著的特征,通过所有权系统(Ownership System)和借用检查器(Borrow Checker)在编译期消除空指针解引用、数据竞争、悬挂指针等常见内存错误;并发是Rust解决多线程编程难题的答案,利用类型系统和所有权机制实现线程间的安全数据共享;实用则体现在Rust对现有生态系统的友好支持、友好的错误提示信息,以及丰富的标准库和第三方 crate(Rust生态中的包/库单位)资源。
> Rust's design philosophy can be summarized as three core principles: Safety, Concurrency, and Practicality. These three principles are not isolated but interwoven and mutually supportive. Safety is Rust's most prominent feature, eliminating common memory errors such as null pointer dereferencing, data races, and dangling pointers at compile time through the ownership system and borrow checker. Concurrency is Rust's answer to solving multi-threaded programming challenges, enabling safe data sharing between threads through the type system and ownership mechanisms. Practicality is reflected in Rust's friendly support for the existing ecosystem, helpful error messages, and rich standard library and third-party crate resources.
在正式踏上Rust学习之路之前,我们需要先完成开发环境的搭建。如同一名工匠需要精心准备工具一样,一位Rust程序员也需要配置一套完善的开发环境。Rust团队为此提供了一站式安装工具——rustup,它不仅负责Rust工具链的安装和更新,还能管理多个Rust版本,支持在不同版本间切换,这对于需要维护不同项目依赖的开发者而言极为便利。
> Before embarking on the Rust learning journey, we need to complete the development environment setup. Just as a craftsman needs to carefully prepare tools, a Rust programmer needs to configure a complete development environment. The Rust team provides a one-stop installation tool—rustup, which is responsible for installing and updating the Rust toolchain, managing multiple Rust versions, and supporting switching between different versions, which is extremely convenient for developers who need to maintain different project dependencies.
1.2 安装Rust工具链 | Installing the Rust Toolchain
1.2.1 在Windows系统上安装 | Installing on Windows
对于Windows用户,Rust官方提供了两种安装方式:通过官方installer(.msi安装包)或者通过rustup-init.exe脚本。对于绝大多数用户,我们推荐使用rustup-init.exe方式,因为它更加灵活且能够自动处理大部分配置工作。
> For Windows users, Rust officially provides two installation methods: through the official installer (.msi package) or via the rustup-init.exe script. For the vast majority of users, we recommend using the rustup-init.exe method because it is more flexible and can automatically handle most configuration work.
首先,访问Rust官方网站下载页面 https://www.rust-lang.org/tools/install,或者直接访问 rustup-init.exe 的下载链接。下载完成后,双击运行该可执行文件。你将看到一个简洁的命令行安装界面。
> First, visit the Rust official website download page at https://www.rust-lang.org/tools/install, or directly access the rustup-init.exe download link. After downloading, double-click to run the executable. You will see a simple command-line installation interface.
```powershell Rustup init 欢迎使用 rustup 安装程序,版本 1.26.0 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
1) 继续(推荐) 2) 自定义安装 3) 取消安装 > ```
安装程序会检测系统环境,询问你是否使用默认配置。对于大多数用户,选择默认配置(选项1)即可。默认配置会安装最新的稳定版Rust(stable)、构建工具(build tools)以及完整的文档。如果你是高级用户,可以选择选项2进行自定义配置,比如指定安装目录、选择不同的工具链通道(stable、beta或nightly)等。
> The installer will detect the system environment and ask if you want to use the default configuration. For most users, selecting the default configuration (option 1) is sufficient. The default configuration will install the latest stable Rust (stable), build tools, and complete documentation. If you are an advanced user, you can choose option 2 for custom configuration, such as specifying the installation directory or choosing different toolchain channels (stable, beta, or nightly).
安装完成后,关闭当前命令行窗口并打开一个新的PowerShell或命令提示符窗口,然后输入以下命令验证安装:
> After installation is complete, close the current command window and open a new PowerShell or Command Prompt window, then enter the following command to verify the installation:
```powershell rustc --version cargo --version ```
如果安装成功,你将看到类似以下的输出:
> If the installation is successful, you will see output similar to the following:
``` rustc 1.75.0 ( cerrone 2024-01-08 ) cargo 1.75.0 ( c cerrone 2024-01-08 ) ```
版本号可能因发布时间而有所不同,但只要显示了版本信息,就说明Rust已经成功安装到你的系统中。
> The version number may vary depending on the release date, but as long as version information is displayed, Rust has been successfully installed on your system.
1.2.2 在Linux和macOS上安装 | Installing on Linux and macOS
对于Linux和macOS用户,Rust提供了统一的安装脚本。你可以通过curl命令直接下载并执行rustup安装脚本:
> For Linux and macOS users, Rust provides a unified installation script. You can directly download and execute the rustup installation script via the curl command:
```bash curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh ```
这个命令的工作原理是:curl从Rust官方服务器下载安装脚本,然后通过管道(pipe)传递给sh命令执行。整个过程是安全的,安装脚本会经过TLS加密传输,且内容来自官方服务器。
> The working principle of this command is: curl downloads the installation script from the Rust official server, then passes it to the sh command through a pipe. The entire process is secure, the installation script is transmitted through TLS encryption, and the content comes from the official server.
安装脚本同样会提供交互式界面:
> The installation script will also provide an interactive interface:
``` 欢迎使用 rustup ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
请选择安装选项(默认选项1):
1) 继续安装 2) 自定义安装 3) 取消安装
> ```
选择默认选项1继续安装。安装完成后,脚本会提示你将Cargo的bin目录(`$HOME/.cargo/bin`)添加到PATH环境变量中。如果你是使用bash的用户,可以执行以下命令使配置生效:
> After the installation is complete, the script will prompt you to add Cargo's bin directory (`$HOME/.cargo/bin`) to the PATH environment variable. If you are a bash user, you can execute the following command to apply the configuration:
```bash source $HOME/.cargo/env ```
或者手动将以下内容添加到你的`~/.bashrc`或`~/.zshrc`文件中:
> Or manually add the following content to your `~/.bashrc` or `~/.zshrc` file:
```bash export PATH="$HOME/.cargo/bin:$PATH" ```
验证安装的命令与Windows相同:
> The command to verify the installation is the same as on Windows:
```bash rustc --version cargo --version ```
1.2.3 理解rustup工具链 | Understanding the rustup Toolchain
rustup不仅仅是一个安装程序,它更是一个强大的Rust工具链管理器。理解rustup的工作原理对于高效使用Rust至关重要。
> rustup is not just an installer; it is a powerful Rust toolchain manager. Understanding how rustup works is essential for efficiently using Rust.
工具链(Toolchain)是Rust工具的完整集合,主要包括以下组件:
> A toolchain is a complete set of Rust tools, mainly including the following components:
- **rustc**:Rust编译器,负责将Rust源代码编译成可执行文件或库文件。
- **cargo**:Rust的项目管理器和构建工具,是Rust开发中最常用的命令。
- **rustfmt**:Rust代码格式化工具,能够自动将代码格式化为符合Rust风格指南的样式。
- **rustdoc**:Rust官方文档生成器,可以从代码注释中生成漂亮的HTML文档。
- **clippy**:Rust的代码质量工具,提供超过300条lint规则来检测代码中的常见错误和不良实践。
> - rustc: The Rust compiler, responsible for compiling Rust source code into executable files or library files. > - cargo: Rust's project manager and build tool, the most commonly used command in Rust development. > - rustfmt: Rust's code formatting tool, capable of automatically formatting code to conform to the Rust style guide. > - rustdoc: Rust's official documentation generator, which can generate beautiful HTML documentation from code comments. > **- clippy: Rust's code quality tool, providing over 300 lint rules to detect common errors and bad practices in code