Share E-Book
Scan to open this page

Scan with your phone to open this page

Author: Steve Klabnik, Carol Nichols

本书的英文原版作者为 Steve Klabnik 和 Carol Nichols,并由 Rust 社区补充完善。本简体中文译本由 Rust 中文社区翻译。 本书假设你使用的是 Rust 1.90.0(2025-09-18 发布)或更高版本,并在所有项目的Cargo.toml 文件中通过 edition = "2024"将其配置为使用 Rust 2024 Edition 惯用法。请查看第一章的 “安装” 部分了解如何安装和升级 Rust,并查看附录 E 了解版本相关的信息。 本书的英文原版 HTML 格式可以在在线阅读;使用rustup 安装的 Rust 也包含一份英文离线版,运行 rustup docs --book 即可打开。 本书还有一些社区翻译版本。(译者注:简体中文译本可以在 在线阅读,PDF 版本请下载 Rust 程序设计语言 简体中文版.pdf)

AI Reading Assistant

Whole-book reading guide from stratified index samples; jump to passages in the text

AI guide
# Rust 程序设计语言 简体中文版 (The Rust Programming Language, 2e) ## 【One-Line Pitch】 The definitive, community-maintained guide to Rust, taking you from your first `Hello, world!` through ownership, traits, and building real projects — essential reading for any programmer serious about systems programming, whether you're coming from C, Python, or JavaScript. ## 【Book Arc】 - **Opening (~0%–10%)**: Installation, Cargo basics (`new`, `build`, `run`, `check`), and a complete "Guessing Game" project that introduces variables, input/output, and `match` — a fast, hands-on on-ramp that shows Rust's workflow before diving into theory. - **Early (~10%–23%)**: Core language fundamentals — variables and mutability, control flow, and the pivotal ownership system (stack vs. heap, borrowing, slices) — followed by structs and enums, establishing the mental model that makes Rust unique. - **Early-to-Middle (~23%–32%)**: Modules and privacy for organizing crates, plus collections (String, Vec, HashMap) with their pitfalls, and error handling — `panic!`, `Result`, and the `?` operator — teaching you to write robust, production-ready code. - **Middle (~39%–48%)**: Generics, traits, and lifetimes — the abstraction toolkit — followed by a thorough testing chapter covering unit tests, integration tests, and test organization, showing how to verify behavior as you build. - **Late (~48% onward)**: A capstone project (building a `grep`-like tool) that synthesizes everything learned, demonstrating how to structure a real binary crate with `src/main.rs` and `src/lib.rs` separation for testability. ## 【Key Takeaways】 - **Cargo is your constant companion** (Opening): `cargo new`, `build`, `run`, and `check` form a fast feedback loop; `cargo check` skips binary generation for quicker compile validation, and `cargo doc --open` gives you local dependency docs. This workflow is identical across all operating systems. - **Ownership is Rust's third way to manage memory** (Early): Unlike garbage collection or manual allocation, Rust uses compile-time rules — values have a single owner, and when that owner goes out of scope, memory is freed. This gives you safety without runtime overhead. - **Stack vs. heap determines behavior** (Early): Stack data needs known, fixed sizes; heap data uses pointers and requires allocation. Understanding this distinction explains why Rust makes the design choices it does — pushing to the stack is fast, while heap access requires pointer indirection. - **Borrowing rules prevent dangling references** (Early): At any time, you can have either one mutable reference or multiple immutable references — never both. References must always be valid, which the compiler enforces, eliminating an entire class of memory bugs. - **`match` is exhaustive by design** (Early): Rust's compiler checks that all possible cases are covered — for example, `Option<T>` forces you to handle `None`. This turns a billion-dollar class of null-pointer bugs into a compile-time error. - **Traits enable abstraction with coherence** (Middle): You can implement your traits for any type, but the orphan rule prevents implementing external traits on external types — ensuring other people's code can't break yours, and vice versa. - **Lifetimes describe relationships, not durations** (Middle): Lifetime annotations like `'a` don't change how long references live; they tell the borrow checker how multiple references relate, enabling it to verify your code's validity. - **Testing is built into the workflow** (Middle): `#[test]` attributes, `cargo test`, unit tests in modules, and integration tests in a `tests/` directory — with the key insight that binary crates need a `src/lib.rs` companion to be testable from integration tests. ## 【Reading Tips】 - **Skim the Guessing Game chapter** (~3%–10%): It's a great warm-up, but don't get bogged down — the real meat starts with ownership. Come back to it if you need a refresher on Cargo basics. - **Deep-read the ownership chapter** (~10%–13%): This is the hardest conceptual leap for most programmers. Read it slowly, work through the examples, and expect to re-read it. The stack/heap analogy (restaurant seating) is worth internalizing. - **Pay attention to compiler errors**: The book shows real error messages throughout — these are teaching tools. Reading them carefully will train you to understand Rust's diagnostics, which are among the best in any language. - **Do the exercises, don't just read**: The book builds projects incrementally (Guessing Game, then a grep clone). Type the code yourself, break it, and fix it — that's where the learning happens. - **Use the testing chapter as a reference** (~42%–48%): You don't need to master every testing feature upfront, but know it's there. The distinction between unit tests (private internals) and integration tests (public API) is a key insight for structuring projects. ## 【Coverage Limits】 This guide covers the book's first half (through ~48%), including fundamentals, ownership, structs/enums, modules, collections, error handling, generics/traits/lifetimes, and testing. The excerpts do not cover the later project chapters, concurrency, smart pointers, or advanced features — those require reading the book directly. ##
Page 20
Cargo 内容: • 可以使用 cargo new 创建项目。 • 可以使用 cargo build 构建项目。 • 可以使用 cargo run 一步构建并运行项目。 • 可以使用 cargo check 在不生成二进制文件的情况下构建项目来检查错误。 • 有别于将构建结果放在与源码相同的目录,Cargo 会...
View in text
Excerpt 2
rait `std::fmt::Display` is not implemented for `Rectangle` = note: in format strings you may be able to use `{:?}` (or {:#?} for pretty- print) instead 让我们来...
View in text
Excerpt 3
`dev` profile [unoptimized + debuginfo] target(s) in 0.27s Running `target/debug/panic` thread 'main' panicked at src/main.rs:4:6: index out of bounds: the l...
View in text
Excerpt 4
result = add(2, 2); assert_eq!(result, 4); } } 示例 11-1:由 cargo new 自动生成的测试模块和函数 文件以一个示例 add 函数开头,这样我们就有东西可以测试。 220/562 Rust 程序设计语言 简体中文版 assert_eq!(add_two(2...
View in text
Excerpt 5
位置,好像它就定义在这个新位置一样。 例如,假设我们创建了一个描述艺术概念的库 art。这个库中包含了一个有两个枚举 PrimaryColor 和 SecondaryColor 的模块 kinds,以及一个包含函数 mix 的模块 utils,如示 例 14-3 所示: 文件名:src/lib.rs //! #...
View in text
Excerpt 6
} println!("Result: {}", *counter.lock().unwrap()); } 示例 16-15: 使用 Arc<T> 包装一个 Mutex<T> 能够实现在多线程之间共享所有权 这段代码会打印出如下: Result: 10 成功了!我们从 0 数到了 10,这好像没啥大不了的,不过一...
View in text
Excerpt 7
编译时确保任何在此上下文中使用的值会实现其 trait 对象的 trait。如此便无需在编译时就 知晓所有可能的类型。 之前提到过,Rust 刻意不将结构体与枚举称为 “对象”,以便与其他语言中的对象相区别。在 结构体或枚举中,结构体字段中的数据和 impl 块中的行为是分开的,不同于其他语言中将数 据和行为组合...
View in text
Excerpt 8
到在一个元组结构 体(第五章 “用没有命名字段的元组结构体来创建不同的类型” 部分介绍了元组结构体)中创 建一个新类型。这个元组结构体带有一个字段作为希望实现 trait 的类型的简单封装。由于这 个封装类型对于 crate 是本地的,这样就可以在这个封装上实现 trait。Newtype 是一个源自 Haske...
View in text
Tags
AI categories
ProgrammingGo
ISBN: 1718503105
Publisher: No Starch Press
Publish Year: 2022
Language: English
Pages: 562
File Format: PDF
File Size: 9.2 MB
Text Preview (First 20 pages)
Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

Generating text preview…