第1章 入门指南 (Getting Started)

2026-09-07 00:00    #读书笔记  

本章内容:安装 Rust、编写第一个程序、使用 Cargo 管理项目。

1.1 安装

Rust 通过 rustup 安装,这是 Rust 版本管理和工具链管理器。

1curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

安装后验证:

1rustc --version   # 输出类似 rustc x.y.z (abcabcabc yyyy-mm-dd)
2cargo --version

额外依赖:Rust 需要一个 C 编译器来链接。Arch 用 pacman -S base-devel,Ubuntu 用 apt install build-essential,macOS 用 xcode-select --install

常用管理命令:

1rustup update          # 更新 Rust
2rustup self uninstall  # 卸载
3rustup doc             # 打开本地离线文档
稳定性保证

Rust 编译器保证向后兼容。本书所有能编译的示例,在新版本中依然能通过编译。

1.2 Hello, World!

创建项目

1mkdir ~/projects
2cd ~/projects
3mkdir hello_world
4cd hello_world

编写代码

文件名:main.rs

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

编译与运行

1rustc main.rs   # 编译:生成二进制文件 main(或 main.exe)
2./main          # 运行:输出 Hello, world!

Rust 是预编译语言(ahead-of-time compiled),编译后的二进制可以独立发给没有安装 Rust 的人运行,跟 C/C++ 一样。

程序剖析

装在不同平台

rustc 编译后生成平台相关的二进制。在 Linux 上生成 main,Windows 上生成 main.exe。Cargo 统一了命令,后面不再区分平台。

1.3 Hello, Cargo!

Cargo 是 Rust 的构建系统包管理器。绝大多数 Rust 项目都用 Cargo。

创建 Cargo 项目

1cargo new hello_cargo
2cd hello_cargo

生成的文件结构:

1hello_cargo/
2├── Cargo.toml       # 项目配置(包名、版本、依赖)
3├── src/
4│   └── main.rs      # 源代码
5└── .gitignore       # Cargo 默认初始化 Git 仓库

Cargo.toml 内容:

1[package]
2name = "hello_cargo"
3version = "0.1.0"
4edition = "2021"        # Rust 大版本号
5
6[dependencies]           # 依赖项写在这里

edition 表示 Rust 的大版本(2015 / 2018 / 2021)。同一 edition 下 Rust 保证向后兼容。本书使用 2021 edition。

常用 Cargo 命令

命令作用
cargo build编译(debug 模式),输出在 target/debug/
cargo run编译 + 运行
cargo check仅检查能否编译,不生成二进制(比 build 快得多)
cargo build --release优化编译(release 模式),输出在 target/release/
1cargo build              # 首次 build,还会生成 Cargo.lock(记录实际依赖版本)
2cargo build              # 再次 build,代码没改则直接跳过
3cargo run                # 修改代码后,run 会自动重新编译再运行
4cargo check              # 开发时建议多用 check,速度更快
5cargo build --release    # 发布前用 release 模式,运行更快但编译更慢
Cargo 对比 rustc

简单项目用 rustccargo 区别不大,但项目变复杂(多文件、多 crate、外部依赖)后,Cargo 的价值就体现出来了。从一开始就习惯用 Cargo。

总结