The Rust Programming Language, 2nd Edition
- Length: 560 pages
- Edition: 2
- Language: English
- Publisher: No Starch Press
- Publication Date: 2023-02-28
- ISBN-10: 1718503105
- ISBN-13: 9781718503106
- Sales Rank: #100658 (See Top 100 Books)
With over 50,000 copies sold, The Rust Programming Language is the quintessential guide to programming in Rust. Thoroughly updated to Rust’s latest version, this edition is considered the language’s official documentation.
The Rust Programming Language “covers everything you could want to know about the language.”—Stack Overflow
Rust has been repeatedly voted “Most Loved Language” on the StackOverflow Developer Survey.
The Rust Programming Language, 2nd Edition is the official guide to Rust 2021: an open source systems programming language that will help you write faster, more reliable software. Rust provides control of low-level details along with high-level ergonomics, allowing you to improve productivity and eliminate the hassle traditionally associated with low-level languages.
Klabnik and Nichols, alumni of the Rust Core Team, share their knowledge to help you get the most out of Rust’s features so that you can create robust and scalable programs. You’ll begin with basics like creating functions, choosing data types, and binding variables, then move on to more advanced concepts, such as:
- Ownership and borrowing, lifetimes, generics, traits, and trait objects to communicate your program’s constraints to the compiler
- Smart pointers and multithreading, and how ownership interacts with them to enable fearless concurrency
- How to use Cargo, Rust’s built-in package manager, to build, document your code, and manage dependencies
- The best ways to test, handle errors, refactor, and take advantage of expressive pattern matching
In addition to the countless code examples, you’ll find three chapters dedicated to building complete projects: a number-guessing game, a Rust implementation of a command line tool, and a multithreaded server.
Title Page Copyright About the Authors 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 Chapter 1: Getting Started Installation Installing rustup on Linux or macOS Installing rustup on Windows Troubleshooting Updating and Uninstalling Local Documentation Hello, World! Creating a Project Directory Writing and Running a Rust Program Anatomy of a Rust Program Compiling and Running Are Separate Steps Hello, Cargo! Creating a Project with Cargo Building and Running a Cargo Project Building for Release Cargo as Convention Summary Chapter 2: Programming a Guessing Game Setting Up a New Project Processing a Guess Storing Values with Variables Receiving User Input Handling Potential Failure with Result Printing Values with println! Placeholders Testing the First Part Generating a Secret Number Using a Crate to Get More Functionality 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 Chapter 3: Common Programming Concepts Variables and Mutability 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 Chapter 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 Chapter 5: Using Structs to Structure Related Data Defining and Instantiating Structs Using the Field Init Shorthand Creating Instances from Other Instances with Struct Update Syntax Using Tuple Structs Without Named Fields to Create Different Types Unit-Like Structs Without Any Fields An Example Program Using Structs Refactoring with Tuples Refactoring with Structs: Adding More Meaning Adding Useful Functionality with Derived Traits Method Syntax Defining Methods Methods with More Parameters Associated Functions Multiple impl Blocks Summary Chapter 6: Enums and Pattern Matching Defining an Enum Enum Values The Option Enum and Its Advantages Over Null Values The match Control Flow Construct Patterns That Bind to Values Matching with Option<T> Matches Are Exhaustive Catch-All Patterns and the _ Placeholder Concise Control Flow with if let Summary Chapter 7: Managing Growing Projects with Packages, Crates, and Modules Packages and Crates Defining Modules to Control Scope and Privacy 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 Large use Lists The Glob Operator Separating Modules into Different Files Summary Chapter 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 What Is a String? Creating a New String Updating a String Indexing into Strings Slicing Strings Methods for Iterating Over Strings Strings Are Not So Simple Storing Keys with Associated Values in Hash Maps Creating a New Hash Map Accessing Values in a Hash Map Hash Maps and Ownership Updating a Hash Map Hashing Functions Summary Chapter 9: Error Handling Unrecoverable Errors with panic! Recoverable Errors with Result Matching on Different Errors Propagating Errors To panic! or Not to panic! Examples, Prototype Code, and Tests Cases in Which You Have More Information Than the Compiler Guidelines for Error Handling Creating Custom Types for Validation Summary Chapter 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 Traits: Defining Shared Behavior Defining a Trait Implementing a Trait on a Type Default Implementations Traits as Parameters Returning Types That Implement Traits Using Trait Bounds to Conditionally Implement Methods Validating References with Lifetimes Preventing Dangling References with Lifetimes The Borrow Checker Generic Lifetimes in Functions Lifetime Annotation Syntax Lifetime Annotations in Function Signatures Thinking in Terms of Lifetimes Lifetime Annotations in Struct Definitions Lifetime Elision Lifetime Annotations in Method Definitions The Static Lifetime Generic Type Parameters, Trait Bounds, and Lifetimes Together Summary Chapter 11: Writing Automated Tests How to Write Tests The Anatomy of a Test Function Checking Results with the assert! Macro Testing Equality with the assert_eq! and assert_ne! Macros Adding Custom Failure Messages Checking for Panics with should_panic 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 Some Tests Unless Specifically Requested Test Organization Unit Tests Integration Tests Summary Chapter 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 Separation of Concerns for Binary Projects Fixing the Error Handling Extracting Logic from main Splitting Code into a Library Crate Developing the Library’s Functionality with Test-Driven Development Writing a Failing Test Writing Code to Pass the Test Working with Environment Variables Writing a Failing Test for the Case-Insensitive Search Function Implementing the search_case_insensitive Function Writing Error Messages to Standard Error Instead of Standard Output Checking Where Errors Are Written Printing Errors to Standard Error Summary Chapter 13: Functional Language Features: Iterators and Closures Closures: Anonymous Functions That Capture Their Environment Capturing the Environment with Closures Closure Type Inference and Annotation Capturing References or Moving Ownership Moving Captured Values Out of Closures and the Fn Traits Processing a Series of Items with Iterators The Iterator Trait and the next Method Methods That Consume the Iterator Methods That Produce Other Iterators Using Closures That Capture Their Environment Improving Our I/O Project Removing a clone Using an Iterator Making Code Clearer with Iterator Adapters Choosing Between Loops and Iterators Comparing Performance: Loops vs. Iterators Summary Chapter 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 with pub use 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 with cargo yank Cargo Workspaces Creating a Workspace Creating the Second Package in the Workspace Installing Binaries with cargo install Extending Cargo with Custom Commands Summary Chapter 15: Smart Pointers Using Box<T> to Point to Data on the Heap Using Box<T> to Store Data on the Heap Enabling Recursive Types with Boxes Treating Smart Pointers Like Regular References with Deref Following the Pointer to the Value Using Box<T> Like a Reference Defining Our Own Smart Pointer Implementing the Deref Trait Implicit Deref Coercions with Functions and Methods How Deref Coercion Interacts with Mutability Running Code on Cleanup with the Drop Trait Rc<T>, the Reference Counted Smart Pointer Using Rc<T> to Share Data Cloning an Rc<T> Increases the Reference Count RefCell<T> and the Interior Mutability Pattern Enforcing Borrowing Rules at Runtime with RefCell<T> Interior Mutability: A Mutable Borrow to an Immutable Value Allowing Multiple Owners of Mutable Data with Rc<T> and RefCell<T> Reference Cycles Can Leak Memory Creating a Reference Cycle Preventing Reference Cycles Using Weak<T> Summary Chapter 16: Fearless Concurrency Using Threads to Run Code Simultaneously Creating a New Thread with spawn Waiting for All Threads to Finish Using join Handles Using move Closures with Threads Using Message Passing to Transfer Data Between Threads Channels and Ownership Transference Sending Multiple Values and Seeing the Receiver Waiting Creating Multiple Producers by Cloning the Transmitter Shared-State Concurrency Using Mutexes to Allow Access to Data from One Thread at a Time Similarities Between RefCell<T>/Rc<T> and Mutex<T>/Arc<T> Extensible Concurrency with the Send and Sync Traits Allowing Transference of Ownership Between Threads with Send Allowing Access from Multiple Threads with Sync Implementing Send and Sync Manually Is Unsafe Summary Chapter 17: 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 That Allow for Values of Different Types Defining a Trait for Common Behavior Implementing the Trait Trait Objects Perform Dynamic Dispatch Implementing an Object-Oriented Design Pattern Defining Post and Creating a New Instance in the Draft State Storing the Text of the Post Content Ensuring the Content of a Draft Post Is Empty Requesting a Review Changes the Post’s State Adding approve to Change the Behavior of content Trade-offs of the State Pattern Summary Chapter 18: Patterns and Matching All the Places Patterns Can Be Used match Arms Conditional if let Expressions while let Conditional Loops for Loops let Statements Function Parameters Refutability: Whether a Pattern Might Fail to Match Pattern Syntax Matching Literals Matching Named Variables Multiple Patterns Matching Ranges of Values with ..= Destructuring to Break Apart Values Ignoring Values in a Pattern Extra Conditionals with Match Guards @ Bindings Summary Chapter 19: Advanced Features Unsafe Rust 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 When to Use Unsafe Code Advanced Traits Associated Types Default Generic Type Parameters and Operator Overloading Disambiguating Between Methods with the Same Name Using Supertraits Using the Newtype Pattern to Implement External Traits Advanced Types Using the Newtype Pattern for Type Safety and Abstraction Creating Type Synonyms with 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 with macro_rules! for General Metaprogramming Procedural Macros for Generating Code from Attributes How to Write a Custom derive Macro Attribute-Like Macros Function-Like Macros Summary Chapter 20: Final Project: Building a Multithreaded Web Server Building a Single-Threaded Web Server Listening to the TCP Connection Reading the Request A Closer Look at an HTTP Request Writing a Response Returning Real HTML Validating the Request and Selectively Responding A Touch of Refactoring Turning Our Single-Threaded Server into 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 Appendix A: Keywords Keywords Currently in Use Keywords Reserved for Future Use Raw Identifiers Appendix B: Operators and Symbols Operators Non-operator Symbols Appendix 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 Appendix D: Useful Development Tools Automatic Formatting with rustfmt Fix Your Code with rustfix More Lints with Clippy IDE Integration Using rust-analyzer Appendix E: Editions Index
Donate to keep this site alive
How to download source code?
1. Go to: https://nostarch.com/
2. Search the book title: The Rust Programming Language, 2nd Edition
, sometime you may not get the results, please search the main title
3. Click the book title in the search results
3. Download the Source Code.
1. Disable the AdBlock plugin. Otherwise, you may not get any links.
2. Solve the CAPTCHA.
3. Click download link.
4. Lead to download server to download.