Author:Steve Klabnik, Carol Nichols
No description
Tags
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.
Page
1
(This page has no text content)
Page
2
CONTENTS IN DETAIL 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
Page
3
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
Page
4
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
Page
5
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 D ifferent 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
Page
6
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, CRAT ES, 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
Page
7
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 Co mpiler Guidelines for Error Handling Creating Custom Types for Validation
Page
8
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 Method s 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
Page
9
Generic Type Parameters, Trait Bounds, and Lifetimes To gether 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 PROG RAM 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
Page
10
Fixing the Error Handling Extracting Logic from main Splitting Code into a Library Crate Developing the Library’s Functionality with Test-Drive n Development Writing a Failing Test Writing Code to Pass the Test Working with Environment Variables Writing a Failing Test for the Case-Insensitive Sear ch Function Implementing the search_case_insensitive Function Writing Error Messages to Standard Error Instead of Sta ndard 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 Enviro nment Capturing the Environment with Closures Closure Type Inference and Annotation Capturing References or Moving Ownership Moving Captured Values Out of Closures and the Fn Tr aits 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
Page
11
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 De ref
Page
12
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 Immutabl e 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 Wait ing
Page
13
Creating Multiple Producers by Cloning the Transmitt er Shared-State Concurrency Using Mutexes to Allow Access to Data from One Threa d at a Time Similarities Between RefCell<T>/Rc<T> and Mutex<T>/A rc<T> Extensible Concurrency with the Send and Sync Traits Allowing Transference of Ownership Between Threads w ith 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 Dra ft 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
Page
14
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
Page
15
Accessing Fields of a Union When to Use Unsafe Code Advanced Traits Associated Types Default Generic Type Parameters and Operator Overloa ding Disambiguating Between Methods with the Same Name Using Supertraits Using the Newtype Pattern to Implement External Trai ts Advanced Types Using the Newtype Pattern for Type Safety and Abstra ction 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 Met aprogramming Procedural Macros for Generating Code from Attribute s How to Write a Custom derive Macro Attribute-Like Macros Function-Like Macros Summary
Page
16
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
Page
17
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
Page
18
THE RUST PROGRAMMING LANGUAGE 2nd Edition by Steve Klabnik and Carol Nichols, with contributions from the Rust Community
Page
19
THE RUST PROGRAMMING LANGUAGE, 2ND EDITION. Copyright © 2023 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. Printed in the United States of America First printing 27 26 25 24 23 1 2 3 4 5 ISBN-13: 978-1-7185-0310-6 (print) ISBN-13: 978-1-7185-0311-3 (ebook) Publisher: William Pollock Managing Editor: Jill Franklin Production Manager: Sabrina Plomitallo-González Production Editors: Jennifer Kepler and Katrina Horlbeck Olsen Developmental Editor: Liz Chadwick Cover Illustration: Karen Rustad Tölva Interior Design: Octopod Studios Technical Reviewer: JT Copyeditor: Audrey Doyle Compositor: Jeff Lytle, Happenstance Type-O-Rama Proofreader: Liz Wheeler For information on distribution, bulk sales, corporate sales, or translations, please contact No Starch Press, Inc. directly at info@nostarch.com or: No Starch Press, Inc. 245 8th Street, San Francisco, CA 94103 phone: 1.415.863.9900 www.nostarch.com The Library of Congress has catalogued the first edition as follows: Names: Klabnik, Steve, author. | Nichols, Carol, 1983- eauthor. 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
Page
20
005.13/3--dc23 LC record available at https://lccn.loc.gov/2018014097 No Starch Press and the No Starch Press 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.
The above is a preview of the first 20 pages. Register to read the complete e-book.
Comments 0
Loading comments...
Reply to Comment
Edit Comment