The Rust Programming Language. 3 Ed

The Rust Programming Language. 3 Ed

The Rust Programming Language. 3 Ed
Автор: Klabnik Steve, Krycho Chris, Nichols Carol
Дата выхода: 2026
Издательство: No Starch Press, Inc.
Количество страниц: 789
Размер файла: 3,3 МБ
Тип файла: PDF
Добавил: codelibs
 Проверить на вирусы

FOREWORD....20

PREFACE....22

ACKNOWLEDGMENTS....23

INTRODUCTION....24

Who Rust Is For....25

Teams of Developers....25

Students....25

Companies....26

Open Source Developers....26

People Who Value Speed and Stability....26

Who This Book Is For....27

How to Use This Book....27

Resources and How to Contribute to This Book....29

1....30

GETTING STARTED....30

Installation....31

Installing rustup on Linux or macOS....31

Installing rustup on Windows....32

Troubleshooting....32

Updating and Uninstalling....33

Reading the Local Documentation....34

Using Text Editors and IDEs....34

Hello, World!....34

Project Directory Setup....35

Rust Program Basics....35

Anatomy of a Rust Program....36

Compilation and Execution....37

Hello, Cargo!....39

Creating a Project with Cargo....39

Building and Running a Cargo Project....41

Building for Release....44

Leveraging Cargo’s Conventions....44

Summary....45

2....46

PROGRAMMING A GUESSING GAME....46

Setting Up a New Project....47

Processing a Guess....48

Storing Values with Variables....49

Receiving User Input....51

Handling Potential Failure with the Result Type....52

Printing Values with println! Placeholders....53

Testing the First Part....54

Generating a Secret Number....54

Increasing Functionality with a Crate....55

Generating a Random Number....58

Comparing the Guess to the Secret Number....60

Allowing Multiple Guesses with Looping....65

Quitting After a Correct Guess....66

Handling Invalid Input....66

Summary....69

3....70

COMMON PROGRAMMING CONCEPTS....70

Variables and Mutability....71

Declaring Constants....73

Shadowing....74

Data Types....76

Scalar Types....77

Compound Types....82

Functions....87

Parameters....88

Statements and Expressions....90

Functions with Return Values....92

Comments....94

Control Flow....95

if Expressions....96

Repetition with Loops....101

Summary....107

4....108

UNDERSTANDING OWNERSHIP....108

What Is Ownership?....109

Ownership Rules....110

Variable Scope....110

The String Type....111

Memory and Allocation....112

Ownership and Functions....123

Return Values and Scope....124

References and Borrowing....126

Mutable References....129

Dangling References....132

The Rules of References....134

The Slice Type....134

String Slices....137

Other Slices....142

Summary....143

5....144

USING STRUCTS TO STRUCTURE RELATED DATA....144

Defining and Instantiating Structs....145

Using the Field Init Shorthand....147

Creating Instances with Struct Update Syntax....148

Creating Different Types with Tuple Structs....149

Defining Unit-Like Structs....150

An Example Program Using Structs....152

Refactoring with Tuples....153

Refactoring with Structs....154

Adding Functionality with Derived Traits....155

Methods....159

Method Syntax....160

Methods with More Parameters....163

Associated Functions....164

Multiple impl Blocks....165

Summary....166

6....167

ENUMS AND PATTERN MATCHING....167

Defining an Enum....168

Enum Values....169

The Option Enum....173

The match Control Flow Construct....176

Patterns That Bind to Values....178

The Option Match Pattern....180

Matches Are Exhaustive....181

Catch-All Patterns and the _ Placeholder....182

Concise Control Flow with if let....184

Staying on the “Happy Path” with let...else....186

Summary....188

7....190

PACKAGES, CRATES, AND MODULES....190

Packages and Crates....192

Control Scope and Privacy with Modules....195

Paths for Referring to an Item in the Module Tree....197

Exposing Paths with the pub Keyword....200

Starting Relative Paths with super....203

Making Structs and Enums Public....204

Bringing Paths into Scope with the use Keyword....206

Creating Idiomatic use Paths....208

Providing New Names with the as Keyword....210

Re-exporting Names with pub use....210

Using External Packages....211

Using Nested Paths to Clean Up use Lists....212

Importing Items with the Glob Operator....214

Separating Modules into Different Files....214

Summary....217

8....218

COMMON COLLECTIONS....218

Storing Lists of Values with Vectors....219

Creating a New Vector....219

Updating a Vector....220

Reading Elements of Vectors....221

Iterating Over the Values in a Vector....223

Using an Enum to Store Multiple Types....224

Dropping a Vector Drops Its Elements....225

Storing UTF-8 Encoded Text with Strings....226

Defining Strings....226

Creating a New String....226

Updating a String....228

Indexing into Strings....231

Slicing Strings....233

Iterating Over Strings....234

Handling the Complexities of Strings....235

Storing Keys with Associated Values in Hash Maps....236

Creating a New Hash Map....236

Accessing Values in a Hash Map....237

Managing Ownership in Hash Maps....238

Updating a Hash Map....238

Hashing Functions....241

Summary....241

9....243

ERROR HANDLING....243

Unrecoverable Errors with the panic! Macro....244

Recoverable Errors with Result....248

Matching on Different Errors....250

Propagating Errors....254

To panic! or Not to panic!....262

Examples, Prototype Code, and Tests....262

When You Have More Information Than the Compiler....263

Guidelines for Error Handling....264

Custom Types for Validation....265

Summary....268

10....269

GENERIC TYPES, TRAITS, AND LIFETIMES....269

Removing Duplication by Extracting a Function....270

Generic Data Types....273

In Function Definitions....273

In Struct Definitions....276

In Enum Definitions....278

In Method Definitions....279

Performance of Code Using Generics....282

Defining Shared Behavior with Traits....283

Defining a Trait....283

Implementing a Trait on a Type....284

Using Default Implementations....287

Using Traits as Parameters....289

Returning Types That Implement Traits....291

Using Trait Bounds to Conditionally Implement Methods....293

Validating References with Lifetimes....295

Dangling References....295

The Borrow Checker....297

Generic Lifetimes in Functions....298

Lifetime Annotation Syntax....299

In Function Signatures....300

Relationships....304

In Struct Definitions....305

Lifetime Elision....306

In Method Definitions....309

The Static Lifetime....310

Generic Type Parameters, Trait Bounds, and Lifetimes....311

Summary....311

11....313

WRITING AUTOMATED TESTS....313

How to Write Tests....314

Structuring Test Functions....315

Checking Results with the assert! Macro....319

Testing Equality with the assert_eq! and assert_ne! Macros....323

Adding Custom Failure Messages....326

Checking for Panics with the should_panic Attribute....328

Using Result in Tests....332

Controlling How Tests Are Run....333

Running Tests in Parallel or Consecutively....334

Showing Function Output....334

Running a Subset of Tests by Name....337

Ignoring Tests Unless Specifically Requested....339

Test Organization....340

Unit Tests....341

Integration Tests....343

Summary....348

12....349

AN I/O PROJECT: BUILDING A COMMAND LINE PROGRAM....349

Accepting Command Line Arguments....350

Reading the Argument Values....351

Saving the Argument Values in Variables....353

Reading a File....354

Refactoring to Improve Modularity and Error Handling....356

Separating Concerns in Binary Projects....357

Fixing the Error Handling....361

Extracting Logic from main....365

Splitting Code into a Library Crate....368

Adding Functionality with Test-Driven Development....370

Writing a Failing Test....370

Writing Code to Pass the Test....373

Working with Environment Variables....376

Writing a Failing Test for Case-Insensitive Search....376

Implementing the search_case_insensitive Function....378

Redirecting Errors to Standard Error....383

Checking Where Errors Are Written....383

Printing Errors to Standard Error....384

Summary....385

13....386

FUNCTIONAL LANGUAGE FEATURES: ITERATORS AND CLOSURES....386

Closures....387

Capturing the Environment....387

Inferring and Annotating Closure Types....390

Capturing References or Moving Ownership....392

Moving Captured Values Out of Closures....395

Processing a Series of Items with Iterators....400

The Iterator Trait and the next Method....401

Methods That Consume the Iterator....403

Methods That Produce Other Iterators....403

Closures That Capture Their Environment....405

Improving Our I/O Project....407

Removing a clone Using an Iterator....407

Clarifying Code with Iterator Adapters....410

Choosing Between Loops and Iterators....412

Performance in Loops vs. Iterators....412

Summary....413

14....414

MORE ABOUT CARGO AND CRATES.IO....414

Customizing Builds with Release Profiles....415

Publishing a Crate to Crates.io....416

Making Useful Documentation Comments....417

Exporting a Convenient Public API....421

Setting Up a Crates.io Account....426

Adding Metadata to a New Crate....427

Publishing to Crates.io....429

Publishing a New Version of an Existing Crate....430

Deprecating Versions from Crates.io....430

Cargo Workspaces....431

Creating a Workspace....431

Creating the Second Package in the Workspace....433

Installing Binaries with cargo install....438

Extending Cargo with Custom Commands....439

Summary....439

15....441

SMART POINTERS....441

Using Box to Point to Data on the Heap....443

Storing Data on the Heap....443

Enabling Recursive Types with Boxes....444

Treating Smart Pointers Like Regular References....450

Following the Reference to the Value....450

Using Box Like a Reference....451

Defining Our Own Smart Pointer....452

Implementing the Deref Trait....453

Using Deref Coercion in Functions and Methods....455

Handling Deref Coercion with Mutable References....457

Running Code on Cleanup with the Drop Trait....458

A Reference-Counted Smart Pointer....462

Sharing Data....463

Cloning to Increase the Reference Count....465

The Interior Mutability Pattern....467

Enforcing Borrowing Rules at Runtime....467

Using Interior Mutability....469

Allowing Multiple Owners of Mutable Data....477

Reference Cycles Can Leak Memory....479

Creating a Reference Cycle....479

Preventing Reference Cycles Using Weak....482

Summary....488

16....490

FEARLESS CONCURRENCY....490

Using Threads to Run Code Simultaneously....492

Creating a New Thread with spawn....493

Waiting for All Threads to Finish....494

Using move Closures with Threads....496

Transfer Data Between Threads with Message Passing....500

Transferring Ownership Through Channels....504

Sending Multiple Values....505

Creating Multiple Producers....506

Shared-State Concurrency....508

Controlling Access with Mutexes....508

Comparing RefCell/Rc and Mutex/Arc....515

Extensible Concurrency with Send and Sync....515

Transferring Ownership Between Threads....516

Accessing from Multiple Threads....516

Implementing Send and Sync Manually Is Unsafe....517

Summary....517

17....518

FUNDAMENTALS OF ASYNCHRONOUS PROGRAMMING....518

Parallelism and Concurrency....521

Futures and the Async Syntax....524

Our First Async Program....525

Defining the page_title Function....526

Executing an Async Function with a Runtime....529

Concurrently Racing Two URLs Against Each Other....532

Applying Concurrency with Async....534

Creating a New Task with spawn_task....534

Sending Data Between Two Tasks....539

Yielding Control to the Runtime....545

Building Our Own Async Abstractions....550

Streams: Futures in Sequence....552

A Closer Look at the Traits for Async....555

The Future Trait....555

The Pin Type and the Unpin Trait....557

The Stream Trait....567

Futures, Tasks, and Threads....569

Summary....572

18....573

OBJECT-ORIENTED PROGRAMMING FEATURES....573

Characteristics of Object-Oriented Languages....574

Objects Contain Data and Behavior....574

Encapsulation That Hides Implementation Details....575

Inheritance as a Type System and as Code Sharing....577

Using Trait Objects to Abstract Over Shared Behavior....578

Defining a Trait for Common Behavior....579

Implementing the Trait....581

Performing Dynamic Dispatch....585

Implementing an Object-Oriented Design Pattern....585

Attempting Traditional Object-Oriented Style....586

Encoding States and Behavior as Types....596

Summary....600

19....602

PATTERNS AND MATCHING....602

All the Places Patterns Can Be Used....603

match Arms....603

let Statements....604

Conditional if let Expressions....606

while let Conditional Loops....607

for Loops....608

Function Parameters....609

Refutability: Whether a Pattern Might Fail to Match....610

Pattern Syntax....612

Matching Literals....613

Matching Named Variables....613

Matching Multiple Patterns....614

Matching Ranges of Values....615

Destructuring to Break Apart Values....616

Ignoring Values in a Pattern....621

Adding Conditionals with Match Guards....626

Using @ Bindings....629

Summary....630

20....631

ADVANCED FEATURES....631

Unsafe Rust....632

Performing Unsafe Superpowers....633

Dereferencing a Raw Pointer....634

Calling an Unsafe Function or Method....636

Accessing or Modifying a Mutable Static Variable....643

Implementing an Unsafe Trait....645

Accessing Fields of a Union....645

Using Miri to Check Unsafe Code....646

Using Unsafe Code Correctly....648

Advanced Traits....648

Defining Traits with Associated Types....648

Using Default Generic Parameters and Operator Overloading....650

Disambiguating Between Identically Named Methods....653

Using Supertraits....658

Implementing External Traits with the Newtype Pattern....660

Advanced Types....662

Type Safety and Abstraction with the Newtype Pattern....662

Type Synonyms and Type Aliases....663

The Never Type That Never Returns....665

Dynamically Sized Types and the Sized Trait....668

Advanced Functions and Closures....670

Function Pointers....670

Returning Closures....672

Macros....675

The Difference Between Macros and Functions....675

Declarative Macros for General Metaprogramming....676

Procedural Macros for Generating Code from Attributes....678

Custom derive Macros....679

Attribute-Like Macros....686

Function-Like Macros....687

Summary....688

21....689

FINAL PROJECT: BUILDING A MULTITHREADED WEB SERVER....689

Building a Single-Threaded Web Server....691

Listening to the TCP Connection....691

Reading the Request....694

Looking More Closely at an HTTP Request....696

Writing a Response....697

Returning Real HTML....699

Validating the Request and Selectively Responding....701

Refactoring....703

From a Single-Threaded to a Multithreaded Server....704

Simulating a Slow Request....705

Improving Throughput with a Thread Pool....706

Graceful Shutdown and Cleanup....726

Implementing the Drop Trait on ThreadPool....727

Signaling to the Threads to Stop Listening for Jobs....729

Summary....733

A....734

KEYWORDS....734

Keywords Currently in Use....735

Keywords Reserved for Future Use....736

Raw Identifiers....737

B....739

OPERATORS AND SYMBOLS....739

Operators....739

Non-operator Symbols....743

C....750

DERIVABLE TRAITS....750

Debug for Programmer Output....751

PartialEq and Eq for Equality Comparisons....752

PartialOrd and Ord for Ordering Comparisons....752

Clone and Copy for Duplicating Values....753

Hash for Mapping a Value to a Value of Fixed Size....754

Default for Default Values....754

D....755

USEFUL DEVELOPMENT TOOLS....755

Automatic Formatting with rustfmt....755

Fix Your Code with rustfix....756

More Lints with Clippy....757

IDE Integration Using rust-analyzer....759

E....760

EDITIONS....760

INDEX....763

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.

Learn how to:

  • Design programs that communicate their invariants to the compiler
  • Use ownership, lifetimes, and traits to model real-world constraints
  • Write concurrent and multithreaded code with confidence and clarity
  • Build, test, document, and refactor projects using Cargo effectively
  • Handle errors explicitly and idiomatically
  • Apply expressive pattern matching to simplify complex logic

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.

New to this edition:

  • Complete async programming chapter
  • Miri for analyzing unsafe code
  • Built on the Rust 2024 Edition
  • Modern Rust idioms, tooling, and practices

Похожее:

Список отзывов:

Нет отзывов к книге.