Share E-Book
Scan to open this page

Scan with your phone to open this page

Author: Steve Klabnik, Carol Nichols, Rust 中文社区译

Rating No ratings yet

前言虽然不是那么明显,但Rust程序设计语言的本质在于赋能(empowerment):无论你现在编写的是 何种代码,Rust能让你在更为广泛的编程领域走得更远,写出自信。 比如,“系统层面”(“systems-level”)的工作,涉及内存管理、数据表示和并发等底层细节。从传统 角度来看,这是一个神秘的编程领域,只为浸润多年的极少数人所触及,也只有他们能避开那些臭名 昭著的陷阱。即使谨慎的实践者,亦唯恐代码出现漏洞、崩溃或损坏。 Rust破除了这些障碍,其消除了旧的陷阱并提供了伴你一路同行的友好、精良的工具。想要“深入” 底层控制的程序员可以使用Rust,无需冒着常见的崩溃或安全漏洞的风险,也无需学习时常改变的工 具链的最新知识。其语言本身更是被设计为自然而然的引导你编写出在运行速度和内存使用上都十分 高效的可靠代码。 已经在从事编写底层代码的程序员可以使用Rust来提升抱负。例如,在Rust中引入并行是相对低风 险的操作:编译器会为你捕获经典的错误。同时你可以自信的采取更为积极的优化,而不会意外引入 崩溃或漏洞。 但Rust并不局限于底层系统编程。其表现力和工效足以令人愉悦的编写出CLI应用、web server和 很多其他类型的代码——在本书中你会看到两个简单示例。使用Rust能将你在一个领域中学习的技 能延伸到另一个领域;你可以学习Rust来编写web应用,接着将同样的技能应用到你的Raspberry Pi(树莓派)上。 本书全面介绍了Rust为用户赋予的能力。其内容平易近人,致力于帮助你提升Rust的知识,并且提 升你作为程序员整体的理解与自信。那么让我们准备深入学习Rust吧(打开新世界的大门:))—— 欢迎加入Rust社区! — Nicholas Matsakis和Aaron Turon

AI Reading Assistant

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

AI guide
# Rust 程序设计语言 简体中文版 — Reading Guide ## 【One-Line Pitch】 The official Rust book (TRPL) in Chinese translation — a comprehensive, beginner-friendly tour of Rust's ownership model, type system, and tooling that empowers you to write fast, memory-safe systems code without the traditional fear of crashes or vulnerabilities. Ideal for programmers new to Rust, especially those coming from C/C++, Python, or JavaScript who want to build CLI tools, web servers, or embedded applications. ## 【Book Arc】 - **Opening (~0%–10%)**: Installation, "Hello, world!" with `rustc`, and the Cargo build system; introduces `main()`, `println!`, variables with `let`/`mut`, and the guessing game project that runs throughout early chapters. - **Early (~10%–23%)**: Core language fundamentals — variables, mutability, constants, scalar/compound types (tuples, arrays), functions, control flow (`if`, `loop`, `while`, `for`), comments, and the critical ownership concept with `String` and slices. - **Early (~23%–29%)**: Structs and enums — defining custom types with named fields, methods in `impl` blocks, associated functions, and the powerful `match` control-flow operator for exhaustive pattern handling. - **Early–Middle (~29%–39%)**: Module system (packages, crates, `mod`, `use`, `pub`), common collections (Vec, String, HashMap), and error handling — `panic!`, `Result<T, E>`, `?` operator, and the newtype pattern for validation. - **Middle (~39%–48%)**: Generics, traits, and lifetimes — the three pillars of Rust's abstraction and safety; covers `impl Trait`, trait objects, default trait implementations, and lifetime elision rules. - **Late (~48%–end)**: Testing with `#[test]`, `assert!`/`assert_eq!`, and integration with Cargo; excerpts do not cover later chapters on closures, iterators, smart pointers, concurrency, or async/await in detail. ## 【Key Takeaways】 - **Ownership is Rust's defining innovation** (Early): every value has a single owner; when the owner goes out of scope, `drop` is called automatically — this eliminates memory leaks and double-free bugs at compile time, not runtime. - **Borrowing and slices prevent whole classes of errors** (Early): references (`&`) let you read data without taking ownership, and string slices (`&str`) provide safe, immutable views into strings — making APIs like `first_word` both safer and more flexible. - **Structs give meaning to data** (Early): refactoring from tuples to named structs (e.g., `Rectangle` with `width`/`height`) makes code self-documenting and prevents index-confusion bugs; methods in `impl` blocks attach behavior to types. - **`match` enforces exhaustive handling** (Early): the compiler checks that all enum variants are covered, turning "forgot a case" bugs into compile-time errors — a huge reliability win over switch statements in other languages. - **The module system scales projects** (Early–Middle): crates → modules → items, with `pub` for visibility and `use` for paths; code defaults to private, which encourages encapsulation and clean APIs. - **Error handling is explicit and type-driven** (Middle): `Result<T, E>` forces you to handle failure paths, while the `?` operator keeps code readable; the `Guess` newtype pattern centralizes validation logic. - **Generics + traits + lifetimes = zero-cost abstraction** (Middle): generic types like `Point<T, U>` work with any type, traits define shared behavior with default implementations, and lifetimes ensure references never outlive their data — all without runtime overhead. - **Testing is built-in and first-class** (Late): `#[test]` attributes, `assert_eq!`/`assert_ne!` macros, and Cargo's `cargo test` make writing and running tests as natural as compiling code. ## 【Reading Tips】 - **Skim the early "Hello, world!" and Cargo setup** (~0%–5%) if you've used any compiled language — but don't skip the ownership chapter (Ch. 4); it's the conceptual foundation everything else builds on. - **Deep-read the ownership, borrowing, and lifetimes chapters** (Early–Middle): these are the hardest parts for newcomers and the most important for writing idiomatic Rust; work through the examples by hand. - **Use the guessing game as a running project** (Opening–Middle): it reappears throughout the book, showing how concepts apply to a real program — code along rather than just reading. - **Pay attention to compiler error messages** (throughout): the book shows real errors (e.g., E0308 mismatched types) and explains how to fix them — this mirrors actual Rust development and trains you to read the compiler's suggestions. - **Skip or skim the 2018 Edition notes** (Opening) if you're using a recent Rust version; focus on the conceptual content, which remains current. ## 【Coverage Limits】 This guide covers the first ~48% of the book in detail (fundamentals through generics/traits/lifetimes and testing). Later chapters on closures, iterators, smart pointers, concurrency, and async/await are not covered by the available excerpts. ##
Excerpt 1
,离线 版则包含在通过 rustup 安装的 Rust 中;运行 rustup docs --book 可以打开。 本书的 纸质版和电子书由 No Starch Press 发行。 前言 https://kaisery.github.io/trpl-zh-cn/print.html 1/525 12/18/21,...
View in text
Excerpt 2
离开作用域后,Rust 自动调用 drop 函数并清理变量的堆内存。不过图 4-2 展示了两个数据指针指向了同一位置。这就有了一个问题:当 s2 和 s1 离开作用域,他们都会尝试 释放相同的内存。这是一个叫做 二次释放(double free)的错误,也是之前提到过的内存安全性 bug 之一。两次释放(相同)内...
View in text
Excerpt 3
-cn/print.html 143/525 12/18/21, 12:32 PM Rust 程序设计语言 简体中文版 如果 push_str 方法获取了 s2 的所有权,就不能在最后一行打印出其值了。好在代码如我们期望那 样工作! push 方法被定义为获取一个单独的字符作为参数,并附加到 String 中。示...
View in text
Excerpt 4
/print.html 196/525 12/18/21, 12:32 PM Rust 程序设计语言 简体中文版 { let r; // ---------+-- 'a let x = 5; // -+-- 'b | r = &x; // | | println!("r: {}", r); // | 示例 10-...
View in text
Excerpt 5
ult = simulated_expensive_calculation(intensity); if intensity < 25 { println!( "Today, do {} pushups!", expensive_result println!( "Next, do {} situps!", ex...
View in text
Excerpt 6
实现: https://kaisery.github.io/trpl-zh-cn/print.html 330/525 12/18/21, 12:32 PM Rust 程序设计语言 简体中文版 enum List { Cons(i32, Box<List>), Nil, } use crate::List::{C...
View in text
Excerpt 7
来重新赋值 post 使得这个实现不再完全遵守面向对象的状态模式:状态间的转换 不再完全封装在 Post 实现中。然而,得益于类型系统和编译时类型检查,我们得到了的是无效状态 是不可能的!这确保了某些特定的 bug,比如显示未发布博文的内容,将在部署到生产环境之前被发 现。 尝试为示例 17-20 之后的 blo...
View in text
Excerpt 8
API 交互即 可,比如向 People 集合增加名字字符串的方法,这样这些代码就无需知道在内部我们将一个 i32 ID 赋予了这个名字了。newtype 模式是一种实现第十七章 “封装隐藏了实现细节” 部分所讨论的隐藏 实现细节的封装的轻量级方法。 类型别名用来创建类型同义词 连同 newtype 模式,Rus...
View in text
Tags
AI categories
Programming LanguageRustBackend
Publisher: No Starch Press
Publish Year: 2018
Language: English
Pages: 525
File Format: PDF
File Size: 17.6 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…