About the Authors....7
Brief Contents....9
Contents in Detail....11
Foreword....21
Preface....23
Acknowledgments....25
Introduction....27
Who Rust Is For....27
Teams of Developers....28
Students....28
Companies....28
Open Source Developers....28
People Who Value Speed and Stability....28
Who This Book Is For....29
How to Use This Book....29
Resources and How to Contribute to This Book....31
Chapter 1: Getting Started....33
Installation....33
Installing rustup on Linux or macOS....34
Installing rustup on Windows....35
Troubleshooting....35
Updating and Uninstalling....36
Reading the Local Documentation....36
Using Text Editors and IDEs....36
Hello, World!....36
Project Directory Setup....36
Rust Program Basics....37
Anatomy of a Rust Program....38
Compilation and Execution....38
Hello, Cargo!....39
Creating a Project with Cargo....40
Building and Running a Cargo Project....41
Building for Release....43
Leveraging Cargos Conventions....43
Summary....44
Chapter 2: Programming A Guessing Game....45
Setting Up a New Project....46
Processing a Guess....46
Storing Values with Variables....47
Receiving User Input....48
Handling Potential Failure with the Result Type....49
Printing Values with println! Placeholders....50
Testing the First Part....51
Generating a Secret Number....51
Increasing Functionality with a Crate....51
Generating a Random Number....54
Comparing the Guess to the Secret Number....55
Allowing Multiple Guesses with Looping....59
Quitting After a Correct Guess....60
Handling Invalid Input....60
Summary....62
Chapter 3: Common Programming Concepts....63
Variables and Mutability....64
Declaring Constants....66
Shadowing....66
Data Types....68
Scalar Types....69
Compound Types....72
Functions....76
Parameters....77
Statements and Expressions....78
Functions with Return Values....80
Comments....81
Control Flow....82
if Expressions....82
Repetition with Loops....86
Summary....91
Chapter 4: Understanding Ownership....93
What Is Ownership?....93
Ownership Rules....95
Variable Scope....95
The String Type....96
Memory and Allocation....97
Ownership and Functions....103
Return Values and Scope....104
References and Borrowing....105
Mutable References....107
Dangling References....110
The Rules of References....112
The Slice Type....112
String Slices....114
Other Slices....118
Summary....118
Chapter 5: Using Structs to Structure Related Data....119
Defining and Instantiating Structs....120
Using the Field Init Shorthand....121
Creating Instances with Struct Update Syntax....122
Creating Different Types with Tuple Structs....123
Defining Unit-Like Structs....124
An Example Program Using Structs....125
Refactoring with Tuples....126
Refactoring with Structs....127
Adding Functionality with Derived Traits....128
Methods....131
Method Syntax....131
Methods with More Parameters....134
Associated Functions....135
Multiple impl Blocks....136
Summary....136
Chapter 6: Enums and Pattern Matching....137
Defining an Enum....138
Enum Values....138
The Option Enum....142
The match Control Flow Construct....144
Patterns That Bind to Values....146
The Option Match Pattern....147
Matches Are Exhaustive....148
Catch-All Patterns and the _ Placeholder....149
Concise Control Flow with if let....150
Staying on the Happy Path with let...else....151
Summary....153
Chapter 7: Packages, Crates, and Modules....155
Packages and Crates....156
Control Scope and Privacy with Modules....159
Paths for Referring to an Item in the Module Tree....161
Exposing Paths with the pub Keyword....163
Starting Relative Paths with super....166
Making Structs and Enums Public....166
Bringing Paths into Scope with the use Keyword....168
Creating Idiomatic use Paths....170
Providing New Names with the as Keyword....171
Re-exporting Names with pub us....172
Using External Packages....172
Using Nested Paths to Clean Up use Lists....173
Importing Items with the Glob Operator....174
Separating Modules into Different Files....175
Summary....177
Chapter 8: Common Collections....179
Storing Lists of Values with Vectors....180
Creating a New Vector....180
Updating a Vector....181
Reading Elements of Vectors....181
Iterating Over the Values in a Vector....183
Using an Enum to Store Multiple Types....184
Dropping a Vector Drops Its Elements....185
Storing UTF-8 Encoded Text with Strings....185
Defining Strings....185
Creating a New String....186
Updating a String....187
Indexing into Strings....189
Slicing Strings....191
Iterating Over Strings....191
Handling the Complexities of Strings....192
Storing Keys with Associated Values in Hash Maps....192
Creating a New Hash Map....193
Accessing Values in a Hash Map....193
Managing Ownership in Hash Maps....194
Updating a Hash Map....195
Hashing Functions....197
Summary....197
Chapter 9: Error Handling....199
Unrecoverable Errors with the panic! Macro....200
Recoverable Errors with Result....203
Matching on Different Errors....205
Propagating Errors....207
To panic! or Not to panic!....213
Examples, Prototype Code, and Tests....214
When You Have More Information Than the Compiler....214
Guidelines for Error Handling....215
Custom Types for Validation....216
Summary....218
Chapter 10: Generic Types, Traits, and Lifetimes....219
Removing Duplication by Extracting a Function....220
Generic Data Types....222
In Function Definitions....223
In Struct Definitions....225
In Enum Definitions....227
In Method Definitions....227
Performance of Code Using Generics....229
Defining Shared Behavior with Traits....230
Defining a Trait....231
Implementing a Trait on a Type....231
Using Default Implementations....233
Using Traits as Parameters....235
Returning Types That Implement Traits....237
Using Trait Bounds to Conditionally Implement Methods....238
Validating References with Lifetimes....239
Dangling References....240
The Borrow Checker....241
Generic Lifetimes in Functions....242
Lifetime Annotation Syntax....243
In Function Signatures....243
Relationships....246
In Struct Definitions....247
Lifetime Elision....248
In Method Definitions....250
The Static Lifetime....251
Generic Type Parameters, Trait Bounds, and Lifetimes....251
Summary....252
Chapter 11: Writing Automated Tests....253
How to Write Tests....254
Structuring Test Functions....254
Checking Results with the assert! Macro....258
Testing Equality with the assert_eq! and assert_ne! Macros....261
Adding Custom Failure Messages....263
Checking for Panics with the should_panic Attribute....265
Using Result in Tests....268
Controlling How Tests Are Run....269
Running Tests in Parallel or Consecutively....269
Showing Function Output....270
Running a Subset of Tests by Name....272
Ignoring Tests Unless Specifically Requested....273
Test Organization....275
Unit Tests....275
Integration Tests....277
Summary....281
Chapter 12: An IO Project: Building A Command Line Program....283
Accepting Command Line Arguments....284
Reading the Argument Values....284
Saving the Argument Values in Variables....286
Reading a File....287
Refactoring to Improve Modularity and Error Handling....288
Separating Concerns in Binary Projects....289
Fixing the Error Handling....293
Extracting Logic from main....296
Splitting Code into a Library Crate....298
Adding Functionality with Test-Driven Development....300
Writing a Failing Test....300
Writing Code to Pass the Test....302
Working with Environment Variables....305
Writing a Failing Test for Case-Insensitive Search....305
Implementing the search_case_insensitive Function....306
Redirecting Errors to Standard Error....310
Checking Where Errors Are Written....310
Printing Errors to Standard Error....311
Summary....312
Chapter 13: Functional Language Features: Iterators and Closures....313
Closures....314
Capturing the Environment....314
Inferring and Annotating Closure Types....316
Capturing References or Moving Ownership....318
Moving Captured Values Out of Closures....320
Processing a Series of Items with Iterators....324
The Iterator Trait and the next Method....325
Methods That Consume the Iterator....326
Methods That Produce Other Iterators....326
Closures That Capture Their Environment....327
Improving Our IO Project....329
Removing a clone Using an Iterator....329
Clarifying Code with Iterator Adapters....332
Choosing Between Loops and Iterators....333
Performance in Loops vs. Iterators....333
Summary....334
Chapter 14: More About Cargo and Crates.io....335
Customizing Builds with Release Profiles....336
Publishing a Crate to Crates.io....337
Making Useful Documentation Comments....337
Exporting a Convenient Public API....340
Setting Up a Crates.io Account....343
Adding Metadata to a New Crate....344
Publishing to Crates.io....345
Publishing a New Version of an Existing Crate....346
Deprecating Versions from Crates.io....346
Cargo Workspaces....347
Creating a Workspace....347
Creating the Second Package in the Workspace....348
Installing Binaries with cargo install....352
Extending Cargo with Custom Commands....353
Summary....353
Chapter 15: Smart Pointers....355
Using Box to Point to Data on the Heap....356
Storing Data on the Heap....357
Enabling Recursive Types with Boxes....357
Treating Smart Pointers Like Regular References....362
Following the Reference to the Value....362
Using Box Like a Reference....363
Defining Our Own Smart Pointer....363
Implementing the Deref Trait....364
Using Deref Coercion in Functions and Methods....365
Handling Deref Coercion with Mutable References....367
Running Code on Cleanup with the Drop Trait....367
A Reference-Counted Smart Pointer....371
Sharing Data....371
Cloning to Increase the Reference Count....373
The Interior Mutability Pattern....374
Enforcing Borrowing Rules at Runtime....375
Using Interior Mutability....376
Allowing Multiple Owners of Mutable Data....382
Reference Cycles Can Leak Memory....383
Creating a Reference Cycle....384
Preventing Reference Cycles Using Weak....386
Summary....391
Chapter 16: Fearless Concurrency....393
Using Threads to Run Code Simultaneously....394
Creating a New Thread with spawn....395
Waiting for All Threads to Finish....396
Using move Closures with Threads....398
Transfer Data Between Threads with Message Passing....401
Transferring Ownership Through Channels....404
Sending Multiple Values....405
Creating Multiple Producers....406
Shared-State Concurrency....407
Controlling Access with Mutexes....407
Comparing RefCellRc and MutexArc....413
Extensible Concurrency with Send and Sync....413
Transferring Ownership Between Threads....414
Accessing from Multiple Threads....414
Implementing Send and Sync Manually Is Unsafe....414
Summary....415
Chapter 17: Fundamentals of Asynchronous Programming....417
Parallelism and Concurrency....419
Futures and the Async Syntax....421
Our First Async Program....422
Defining the page_title Function....422
Executing an Async Function with a Runtime....425
Concurrently Racing Two URLs Against Each Other....427
Applying Concurrency with Async....429
Creating a New Task with spawn_task....429
Sending Data Between Two Tasks....432
Yielding Control to the Runtime....437
Building Our Own Async Abstractions....441
Streams: Futures in Sequence....443
A Closer Look at the Traits for Async....445
The Future Trait....445
The Pin Type and the Unpin Trait....447
The Stream Trait....453
Futures, Tasks, and Threads....455
Summary....457
Chapter 18: Object-Oriented Programming Features....459
Characteristics of Object-Oriented Languages....460
Objects Contain Data and Behavior....460
Encapsulation That Hides Implementation Details....460
Inheritance as a Type System and as Code Sharing....462
Using Trait Objects to Abstract Over Shared Behavior....463
Defining a Trait for Common Behavior....464
Implementing the Trait....465
Performing Dynamic Dispatch....468
Implementing an Object-Oriented Design Pattern....469
Attempting Traditional Object-Oriented Style....469
Encoding States and Behavior as Types....478
Summary....481
Chapter 19: Patterns and Matching....483
All the Places Patterns Can Be Used....484
match Arms....484
let Statements....485
Conditional if let Expressions....486
while let Conditional Loops....487
for Loops....488
Function Parameters....488
Refutability: Whether a Pattern Might Fail to Match....489
Pattern Syntax....491
Matching Literals....491
Matching Named Variables....491
Matching Multiple Patterns....492
Matching Ranges of Values....493
Destructuring to Break Apart Values....493
Ignoring Values in a Pattern....497
Adding Conditionals with Match Guards....502
Using Bindings....504
Summary....505
Chapter 20: Advanced Features....507
Unsafe Rust....508
Performing Unsafe Superpowers....508
Dereferencing a Raw Pointer....509
Calling an Unsafe Function or Method....511
Accessing or Modifying a Mutable Static Variable....516
Implementing an Unsafe Trait....517
Accessing Fields of a Union....518
Using Miri to Check Unsafe Code....518
Using Unsafe Code Correctly....520
Advanced Traits....520
Defining Traits with Associated Types....520
Using Default Generic Parameters and Operator Overloading....521
Disambiguating Between Identically Named Methods....524
Using Supertraits....527
Implementing External Traits with the Newtype Pattern....529
Advanced Types....530
Type Safety and Abstraction with the Newtype Pattern....530
Type Synonyms and Type Aliases....531
The Never Type That Never Returns....533
Dynamically Sized Types and the Sized Trait....534
Advanced Functions and Closures....536
Function Pointers....536
Returning Closures....538
Macros....540
The Difference Between Macros and Functions....540
Declarative Macros for General Metaprogramming....541
Procedural Macros for Generating Code from Attributes....543
Custom derive Macros....543
Attribute-Like Macros....549
Function-Like Macros....549
Summary....550
Chapter 21: Final Project: Building A Multithreaded Web Server....551
Building a Single-Threaded Web Server....552
Listening to the TCP Connection....553
Reading the Request....555
Looking More Closely at an HTTP Request....556
Writing a Response....557
Returning Real HTML....558
Validating the Request and Selectively Responding....560
Refactoring....562
From a Single-Threaded to a Multithreaded Server....563
Simulating a Slow Request....563
Improving Throughput with a Thread Pool....564
Graceful Shutdown and Cleanup....580
Implementing the Drop Trait on ThreadPool....580
Signaling to the Threads to Stop Listening for Jobs....582
Summary....585
Appendix A: Keywords....587
Keywords Currently in Use....587
Keywords Reserved for Future Use....589
Raw Identifiers....589
Appendix B: Operators and Symbols....591
Operators....591
Non-operator Symbols....594
Appendix C: Derivable Traits....599
Debug for Programmer Output....600
PartialEq and Eq for Equality Comparisons....600
PartialOrd and Ord for Ordering Comparisons....601
Clone and Copy for Duplicating Values....601
Hash for Mapping a Value to a Value of Fixed Size....602
Default for Default Values....602
Appendix D: Useful Development Tools....603
Automatic Formatting with rustfmt....603
Fix Your Code with rustfix....604
More Lints with Clippy....605
IDE Integration Using rust-analyzer....606
Appendix E: Editions....607
Index....609
Build stable, production-grade systems with Rust.
The Rust Programming Language, 3rd Edition, teaches you to write code that the compiler can verify, teams can maintain, and systems can evolve safely over time. Written by longtime Rust community members, this book shows you how to work effectively with Rust’s type system, concurrency model, and tooling, using patterns and idioms chosen for long-term stability.
Three substantial project chapters—focusing on a number-guessing game, a command-line tool, and a multithreaded server—demonstrate how these concepts work together in complete, real programs.
Whether you’re new to Rust or already using it in production, this book helps you write code that scales safely and makes its guarantees explicit.