Statistics
9
Views
0
Downloads
0
Donations
Support
Share
Uploader

高宏飞

Shared on 2026-03-23
Support Statistics
¥.00 · 0times
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.

(This page has no text content)
CONTENTS IN DETAIL FOREWORD PREFACE ACKNOWLEDGMENTS INTRODUCTION Who Rust Is For Teams of Developers Students Companies Open Source Developers People Who Value Speed and Stability Who This Book Is For How to Use This Book Resources and How to Contribute to This Book 1 GETTING STARTED Installation Installing rustup on Linux or macOS Installing rustup on Windows Troubleshooting Updating and Uninstalling Reading the Local Documentation Using Text Editors and IDEs Hello, World! Project Directory Setup Rust Program Basics Anatomy of a Rust Program Compilation and Execution Hello, Cargo! Creating a Project with Cargo
Building and Running a Cargo Project Building for Release Leveraging Cargo’s Conventions Summary 2 PROGRAMMING A GUESSING GAME Setting Up a New Project Processing a Guess Storing Values with Variables Receiving User Input Handling Potential Failure with the Result Type Printing Values with println! Placeholders Testing the First Part Generating a Secret Number Increasing Functionality with a Crate Generating a Random Number Comparing the Guess to the Secret Number Allowing Multiple Guesses with Looping Quitting After a Correct Guess Handling Invalid Input Summary 3 COMMON PROGRAMMING CONCEPTS Variables and Mutability Declaring Constants Shadowing Data Types Scalar Types Compound Types Functions Parameters Statements and Expressions Functions with Return Values Comments Control Flow if Expressions Repetition with Loops Summary 4 UNDERSTANDING OWNERSHIP What Is Ownership? Ownership Rules
Variable Scope The String Type Memory and Allocation Ownership and Functions Return Values and Scope References and Borrowing Mutable References Dangling References The Rules of References The Slice Type String Slices Other Slices Summary 5 USING STRUCTS TO STRUCTURE RELATED DATA Defining and Instantiating Structs Using the Field Init Shorthand Creating Instances with Struct Update Syntax Creating Different Types with Tuple Structs Defining Unit-Like Structs An Example Program Using Structs Refactoring with Tuples Refactoring with Structs Adding Functionality with Derived Traits Methods Method Syntax Methods with More Parameters Associated Functions Multiple impl Blocks Summary 6 ENUMS AND PATTERN MATCHING Defining an Enum Enum Values The Option Enum The match Control Flow Construct Patterns That Bind to Values The Option<T> Match Pattern Matches Are Exhaustive Catch-All Patterns and the _ Placeholder Concise Control Flow with if let Staying on the “Happy Path” with let...else Summary
7 PACKAGES, CRATES, AND MODULES Packages and Crates Control Scope and Privacy with Modules Paths for Referring to an Item in the Module Tree Exposing Paths with the pub Keyword Starting Relative Paths with super Making Structs and Enums Public Bringing Paths into Scope with the use Keyword Creating Idiomatic use Paths Providing New Names with the as Keyword Re-exporting Names with pub use Using External Packages Using Nested Paths to Clean Up use Lists Importing Items with the Glob Operator Separating Modules into Different Files Summary 8 COMMON COLLECTIONS Storing Lists of Values with Vectors Creating a New Vector Updating a Vector Reading Elements of Vectors Iterating Over the Values in a Vector Using an Enum to Store Multiple Types Dropping a Vector Drops Its Elements Storing UTF-8 Encoded Text with Strings Defining Strings Creating a New String Updating a String Indexing into Strings Slicing Strings Iterating Over Strings Handling the Complexities of Strings Storing Keys with Associated Values in Hash Maps Creating a New Hash Map Accessing Values in a Hash Map Managing Ownership in Hash Maps Updating a Hash Map Hashing Functions Summary 9 ERROR HANDLING
Unrecoverable Errors with the panic! Macro Recoverable Errors with Result Matching on Different Errors Propagating Errors To panic! or Not to panic! Examples, Prototype Code, and Tests When You Have More Information Than the Compiler Guidelines for Error Handling Custom Types for Validation Summary 10 GENERIC TYPES, TRAITS, AND LIFETIMES Removing Duplication by Extracting a Function Generic Data Types In Function Definitions In Struct Definitions In Enum Definitions In Method Definitions Performance of Code Using Generics Defining Shared Behavior with Traits Defining a Trait Implementing a Trait on a Type Using Default Implementations Using Traits as Parameters Returning Types That Implement Traits Using Trait Bounds to Conditionally Implement Methods Validating References with Lifetimes Dangling References The Borrow Checker Generic Lifetimes in Functions Lifetime Annotation Syntax In Function Signatures Relationships In Struct Definitions Lifetime Elision In Method Definitions The Static Lifetime Generic Type Parameters, Trait Bounds, and Lifetimes Summary 11 WRITING AUTOMATED TESTS How to Write Tests Structuring Test Functions Checking Results with the assert! Macro
Testing Equality with the assert_eq! and assert_ne! Macros Adding Custom Failure Messages Checking for Panics with the should_panic Attribute Using Result<T, E> in Tests Controlling How Tests Are Run Running Tests in Parallel or Consecutively Showing Function Output Running a Subset of Tests by Name Ignoring Tests Unless Specifically Requested Test Organization Unit Tests Integration Tests Summary 12 AN I/O PROJECT: BUILDING A COMMAND LINE PROGRAM Accepting Command Line Arguments Reading the Argument Values Saving the Argument Values in Variables Reading a File Refactoring to Improve Modularity and Error Handling Separating Concerns in Binary Projects Fixing the Error Handling Extracting Logic from main Splitting Code into a Library Crate Adding Functionality with Test-Driven Development Writing a Failing Test Writing Code to Pass the Test Working with Environment Variables Writing a Failing Test for Case-Insensitive Search Implementing the search_case_insensitive Function Redirecting Errors to Standard Error Checking Where Errors Are Written Printing Errors to Standard Error Summary 13 FUNCTIONAL LANGUAGE FEATURES: ITERATORS AND CLOSURES Closures Capturing the Environment Inferring and Annotating Closure Types Capturing References or Moving Ownership Moving Captured Values Out of Closures
Processing a Series of Items with Iterators The Iterator Trait and the next Method Methods That Consume the Iterator Methods That Produce Other Iterators Closures That Capture Their Environment Improving Our I/O Project Removing a clone Using an Iterator Clarifying Code with Iterator Adapters Choosing Between Loops and Iterators Performance in Loops vs. Iterators Summary 14 MORE ABOUT CARGO AND CRATES.IO Customizing Builds with Release Profiles Publishing a Crate to Crates.io Making Useful Documentation Comments Exporting a Convenient Public API Setting Up a Crates.io Account Adding Metadata to a New Crate Publishing to Crates.io Publishing a New Version of an Existing Crate Deprecating Versions from Crates.io Cargo Workspaces Creating a Workspace Creating the Second Package in the Workspace Installing Binaries with cargo install Extending Cargo with Custom Commands Summary 15 SMART POINTERS Using Box<T> to Point to Data on the Heap Storing Data on the Heap Enabling Recursive Types with Boxes Treating Smart Pointers Like Regular References Following the Reference to the Value Using Box<T> Like a Reference Defining Our Own Smart Pointer Implementing the Deref Trait Using Deref Coercion in Functions and Methods Handling Deref Coercion with Mutable References Running Code on Cleanup with the Drop Trait A Reference-Counted Smart Pointer Sharing Data Cloning to Increase the Reference Count
The Interior Mutability Pattern Enforcing Borrowing Rules at Runtime Using Interior Mutability Allowing Multiple Owners of Mutable Data Reference Cycles Can Leak Memory Creating a Reference Cycle Preventing Reference Cycles Using Weak<T> Summary 16 FEARLESS CONCURRENCY Using Threads to Run Code Simultaneously Creating a New Thread with spawn Waiting for All Threads to Finish Using move Closures with Threads Transfer Data Between Threads with Message Passing Transferring Ownership Through Channels Sending Multiple Values Creating Multiple Producers Shared-State Concurrency Controlling Access with Mutexes Comparing RefCell<T>/Rc<T> and Mutex<T>/Arc<T> Extensible Concurrency with Send and Sync Transferring Ownership Between Threads Accessing from Multiple Threads Implementing Send and Sync Manually Is Unsafe Summary 17 FUNDAMENTALS OF ASYNCHRONOUS PROGRAMMING Parallelism and Concurrency Futures and the Async Syntax Our First Async Program Defining the page_title Function Executing an Async Function with a Runtime Concurrently Racing Two URLs Against Each Other Applying Concurrency with Async Creating a New Task with spawn_task Sending Data Between Two Tasks Yielding Control to the Runtime Building Our Own Async Abstractions Streams: Futures in Sequence A Closer Look at the Traits for Async The Future Trait The Pin Type and the Unpin Trait The Stream Trait
Futures, Tasks, and Threads Summary 18 OBJECT-ORIENTED PROGRAMMING FEATURES Characteristics of Object-Oriented Languages Objects Contain Data and Behavior Encapsulation That Hides Implementation Details Inheritance as a Type System and as Code Sharing Using Trait Objects to Abstract Over Shared Behavior Defining a Trait for Common Behavior Implementing the Trait Performing Dynamic Dispatch Implementing an Object-Oriented Design Pattern Attempting Traditional Object-Oriented Style Encoding States and Behavior as Types Summary 19 PATTERNS AND MATCHING All the Places Patterns Can Be Used match Arms let Statements Conditional if let Expressions while let Conditional Loops for Loops Function Parameters Refutability: Whether a Pattern Might Fail to Match Pattern Syntax Matching Literals Matching Named Variables Matching Multiple Patterns Matching Ranges of Values Destructuring to Break Apart Values Ignoring Values in a Pattern Adding Conditionals with Match Guards Using @ Bindings Summary 20 ADVANCED FEATURES Unsafe Rust Performing Unsafe Superpowers Dereferencing a Raw Pointer Calling an Unsafe Function or Method
Accessing or Modifying a Mutable Static Variable Implementing an Unsafe Trait Accessing Fields of a Union Using Miri to Check Unsafe Code Using Unsafe Code Correctly Advanced Traits Defining Traits with Associated Types Using Default Generic Parameters and Operator Overloading Disambiguating Between Identically Named Methods Using Supertraits Implementing External Traits with the Newtype Pattern Advanced Types Type Safety and Abstraction with the Newtype Pattern Type Synonyms and Type Aliases The Never Type That Never Returns Dynamically Sized Types and the Sized Trait Advanced Functions and Closures Function Pointers Returning Closures Macros The Difference Between Macros and Functions Declarative Macros for General Metaprogramming Procedural Macros for Generating Code from Attributes Custom derive Macros Attribute-Like Macros Function-Like Macros Summary 21 FINAL PROJECT: BUILDING A MULTITHREADED WEB SERVER Building a Single-Threaded Web Server Listening to the TCP Connection Reading the Request Looking More Closely at an HTTP Request Writing a Response Returning Real HTML Validating the Request and Selectively Responding Refactoring From a Single-Threaded to a Multithreaded Server Simulating a Slow Request Improving Throughput with a Thread Pool Graceful Shutdown and Cleanup Implementing the Drop Trait on ThreadPool Signaling to the Threads to Stop Listening for Jobs Summary
A KEYWORDS Keywords Currently in Use Keywords Reserved for Future Use Raw Identifiers B OPERATORS AND SYMBOLS Operators Non-operator Symbols C DERIVABLE TRAITS Debug for Programmer Output PartialEq and Eq for Equality Comparisons PartialOrd and Ord for Ordering Comparisons Clone and Copy for Duplicating Values Hash for Mapping a Value to a Value of Fixed Size Default for Default Values D USEFUL DEVELOPMENT TOOLS Automatic Formatting with rustfmt Fix Your Code with rustfix More Lints with Clippy IDE Integration Using rust-analyzer E EDITIONS INDEX
PRAISE FOR THE RUST PROGRAMMING LANGUAGE “The new material in this edition is particularly strong.” —MICHAEL SNOYMAN, AUTHOR OF RUST FOR BEGINNERS “The Rust Programming Language has always been, and continues to be, the first place I point anyone looking to learn Rust ... a solid introduction to the best Rust has to offer for years to come.” —JON GJENGSET, AUTHOR OF RUST FOR RUSTACEANS “Whether an experienced or a new Rustacean, [The Rust Programming Language is] an invaluable resource on how Rust works.” —MICHAEL GATTOZZI, SENIOR SOFTWARE ENGINEER AT FASTLY “A great resource for mastering Rust’s fundamentals.... If you’re thinking about seriously learning Rust, this book is for you.” —ADAM VARTANIAN, ENGINEERING MANAGER AT CORD “An excellent addition to a programmer’s personal library.” —JARED WOLFF, OWNER, CIRCUIT DOJO LLC
THE RUST PROGRAMMING LANGUAGE 3rd Edition by Steve Klabnik, Carol Nichols, and Chris Krycho, with contributions from the Rust Community San Francisco
THE RUST PROGRAMMING LANGUAGE, 3RD EDITION. Copyright © 2026 by the Rust Foundation and the Rust Project Developers. All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright owner and the publisher. First printing 30 29 28 27 26     1 2 3 4 5 ISBN-13: 978-1-7185-0444-8 (print) ISBN-13: 978-1-7185-0445-5 (ebook) Published by No Starch Press®, Inc. 245 8th Street, San Francisco, CA 94103 phone: +1.415.863.9900 www.nostarch.com; info@nostarch.com Publisher: William Pollock Managing Editor: Jill Franklin Production Manager: Sabrina Plomitallo-González Production Editors: Allison Felus and Miles Bond Developmental Editors: Jill Franklin, Rachel Monaghan, and Eva Morrow Cover Illustrator: Karen Rustad Tölva Interior Design: Octopod Studios Technical Reviewer: Sophia Turner Copyeditor: Audrey Doyle Proofreader: Lisa McCoy The Library of Congress has cataloged the first edition as follows: Names: Klabnik, Steve, author. | Nichols, Carol, 1983- author. Title: The Rust programming language / by Steve Klabnik and Carol Nichols ; with contributions from the Rust Community. Description: San Francisco : No Starch Press, Inc., 2018. | Includes index. Identifiers: LCCN 2018014097 (print) | LCCN 2018019844 (ebook) | ISBN 9781593278519 (epub) | ISBN 1593278519 (epub) | ISBN 9781593278281 (paperback) | ISBN 1593278284 (paperback) Subjects: LCSH: Rust (Computer programming language) | BISAC: COMPUTERS / Programming / Open Source. | COMPUTERS / Programming Languages / General. | COMPUTERS / Programming / General. Classification: LCC QA76.73.R87 (ebook) | LCC QA76.73.R87 K53 2018 (print) | DDC 005.13/3--dc23 LC record available at https://lccn.loc.gov/2018014097
For customer service inquiries, please contact info@nostarch.com. For information on distribution, bulk sales, corporate sales, or translations: sales@nostarch.com. For permission to translate this work: rights@nostarch.com. The authorized representative in the EU for product safety and compliance is EU Compliance Partner, Pärnu mnt. 139b-14, 11317 Tallinn, Estonia, hello@eucompliancepartner.com, +3375690241. No Starch Press and the No Starch Press iron logo are registered trademarks of No Starch Press, Inc. Other product and company names mentioned herein may be the trademarks of their respective owners. Rather than use a trademark symbol with every occurrence of a trademarked name, we are using the names only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The information in this book is distributed on an “As Is” basis, without warranty. While every precaution has been taken in the preparation of this work, neither the authors nor No Starch Press, Inc. shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in it.
About the Authors Steve Klabnik was the lead for the Rust documentation team and was one of Rust’s core developers. A frequent speaker and a prolific open source contributor, he previously worked on projects such as Ruby and Ruby on Rails. Carol Nichols is a member of the Rust Crates.io Team and a former member of the Rust Core Team. She’s a co- founder of Integer 32, LLC, the world’s first Rust-focused software consultancy. She has also organized the Rust Belt Rust Conference. Chris Krycho is a software engineering leader with experience in avionics, developer tools, web frameworks, and more. In addition to his open source software contributions and regular public speaking, he created the New Rustacean podcast (2015–2019). About the Technical Reviewer Sophia Turner has been a longtime advocate of better programming languages and tools. She helped create TypeScript and later joined Mozilla to work on compiler errors, IDE support, and the larger Rust ergonomics initiative. She also served on the Rust Core Team and helped create the Rust Leadership Council.
FOREWORD The Rust programming language has come a long way in a few short years, from its creation and incubation by a small and nascent community of enthusiasts, to becoming one of the most loved and in-demand programming languages in the world. Looking back, it was inevitable that the power and promise of Rust would turn heads and gain a foothold in systems programming. What was not inevitable was the global growth in interest and innovation that permeated through open source communities and catalyzed wide-scale adoption across industries. At this point in time, it is easy to point to the wonderful features that Rust has to offer to explain this explosion in interest and adoption. Who doesn’t want memory safety, and fast performance, and a friendly compiler, and great tooling, among a host of other wonderful features? The Rust language you see today combines years of research in systems programming with the practical wisdom of a vibrant and passionate community. This language was designed with purpose and crafted with care, offering developers a tool that makes it easier to write safe, fast, and reliable code. But what makes Rust truly special is its roots in empowering you, the user, to achieve your goals. This is a language that wants you to succeed, and the principle of empowerment runs through the core of the community that builds, maintains, and advocates for this language. Since
the previous edition of this definitive text, Rust has further developed into a truly global and trusted language. The Rust Project is now robustly supported by the Rust Foundation, which also invests in key initiatives to ensure that Rust is secure, stable, and sustainable. This edition of The Rust Programming Language is a comprehensive update, reflecting the language’s evolution over the years and providing valuable new information. But it is not just a guide to syntax and libraries—it’s an invitation to join a community that values quality, performance, and thoughtful design. Whether you’re a seasoned developer looking to explore Rust for the first time or an experienced Rustacean looking to refine your skills, this edition offers something for everyone. The Rust journey has been one of collaboration, learning, and iteration. The growth of the language and its ecosystem is a direct reflection of the vibrant, diverse community behind it. The contributions of thousands of developers, from core language designers to casual contributors, are what make Rust such a unique and powerful tool. By picking up this book, you’re not just learning a new programming language—you’re joining a movement to make software better, safer, and more enjoyable to work with. Welcome to the Rust community! Bec Rumbul Executive Director of the Rust Foundation
PREFACE This version of the text assumes you’re using Rust 1.85.0 (released 2025-02-17) or later with edition = "2024" in the Cargo.toml file of all projects to configure them to use Rust 2024 edition idioms. See “Installation” on page 1 for instructions on installing or updating Rust, and see Appendix E for information on editions. The 2024 edition of the Rust language includes a number of improvements that make Rust more ergonomic and that correct some inconsistencies. On top of a general update to reflect these improvements, this edition of the book has a number of improvements to address specific feedback: A new Chapter 17 introduces async programming in Rust, including async and await along with the Future and Stream traits. Later chapters have been lightly adapted and renumbered to account for this update. Chapter 20 (Chapter 19 in previous editions) now includes an introduction to Miri, Rust’s dynamic analysis tool for unsafe code. We fixed a number of small errors and imprecise wording throughout the book. Thank you to the readers who reported them! Note that any code from earlier renditions of this book that compiled will continue to compile with the relevant