Rust - 环境设置
Rust - 环境搭建
Section titled “Rust - 环境搭建”得益于官方工具 rustup,搭建现代 Rust 开发环境非常简单。rustup 用于管理 Rust 版本和相关工具。本指南将引导你在任何主要操作系统上完成此过程。
步骤 1:安装 rustup
Section titled “步骤 1:安装 rustup”rustup 会安装 Rust 编译器(rustc)、包管理器和构建工具(cargo)、标准库文档(rust-doc)等。
在 Linux 和 macOS 上
Section titled “在 Linux 和 macOS 上”打开终端并运行以下命令。它将下载一个脚本并开始安装。
$ curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh你会被提示选择安装类型。对于大多数用户来说,推荐选择默认选项(1)。如果安装成功,你将看到:
Rust is installed now. Great!安装程序还会尝试配置你的 shell 的 PATH 环境变量。你可能需要重启终端或运行 source $HOME/.cargo/env 才能使更改生效。
在 Windows 上
Section titled “在 Windows 上”Windows 上的 Rust 需要 Microsoft C++ 构建工具(Build Tools)。你不需要完整的 Visual Studio IDE。
- 访问官方 Visual Studio 下载页面 并获取“Build Tools for Visual Studio”。
- 运行安装程序。在“工作负载(Workloads)”选项卡中,选择“C++ 构建工具”,并确保右侧已选择最新的 Windows SDK 和 C++ 工具集。然后点击安装。
- 安装完构建工具后,访问官方 Rust 网站 并下载
rustup-init.exe。 - 运行
rustup-init.exe。它将引导你完成安装过程。默认设置对大多数用户来说是没问题的。
步骤 2:验证安装
Section titled “步骤 2:验证安装”安装完成后,打开一个新的终端并检查已安装工具的版本。你的版本号可能不同,这完全正常。
# Check the Rust compiler version$ rustc --versionrustc 1.78.0 (9b00956e5 2024-04-29)
# Check the Cargo version$ cargo --versioncargo 1.78.0 (54d881520 2024-04-01)步骤 3:使用 Cargo 运行你的第一个 Rust 程序
Section titled “步骤 3:使用 Cargo 运行你的第一个 Rust 程序”Cargo 是 Rust 生态系统的核心。它处理项目创建、代码编译、依赖管理、运行测试等。你应该始终使用 Cargo 来创建新的 Rust 项目。
- 创建一个新项目:
cargo new hello_world - 进入项目目录:
cd hello_world - 构建项目:
cargo build - 运行项目:
cargo run
$ cargo new hello_world Created binary (application) `hello_world` package$ cd hello_world$ cargo run Compiling hello_world v0.1.0 (/path/to/hello_world) Finished dev [unoptimized + debuginfo] target(s) in 0.50s Running `target/debug/hello_world`Hello, world!基本 Cargo 命令
Section titled “基本 Cargo 命令”熟悉这些命令,因为你将每天使用它们:
cargo new <name>:创建一个新的可执行 Rust 项目。cargo new <name> --lib:创建一个新的库项目。cargo build:在调试模式下编译你的项目。cargo build --release:编译你的项目,并为生产环境进行优化。cargo run:编译并运行你的项目。cargo check:快速检查你的代码是否有错误,而不生成可执行文件。cargo test:运行项目中的所有测试。cargo fmt:根据官方 Rust 风格指南格式化你的代码。cargo clippy:一个强大的代码检查工具(linter),可以发现常见错误并提出改进建议。
保持 Rust 更新
Section titled “保持 Rust 更新”Rust 有一个快速的 6 周发布周期。要将你的 Rust 工具链(toolchain)更新到最新版本,只需运行:
$ rustup update使用在线演练场
Section titled “使用在线演练场”对于无需本地设置的快速实验,你可以使用官方的 Rust 在线演练场(Rust Playground) 或 Tutorialspoint 编程平台(Coding Ground)。它们非常适合测试小型代码片段和共享代码。