在好例子网,分享、交流、成长!
您当前所在位置:首页Others 开发实例一般编程问题 → rust编程语言_The.Rust.Programming.Language.2nd.Edition.2022.12

rust编程语言_The.Rust.Programming.Language.2nd.Edition.2022.12

一般编程问题

下载此实例
  • 开发语言:Others
  • 实例大小:1.59M
  • 下载次数:6
  • 浏览次数:43
  • 发布时间:2023-02-06
  • 实例类别:一般编程问题
  • 发 布 人:mfhaolizi
  • 文件格式:.epub
  • 所需积分:2
 相关标签: 编程语言 rust ST 编程 语言

实例介绍

【实例简介】rust编程语言_The.Rust.Programming.Language.2nd.Edition.2022.12

【实例截图】

from clipboard

from clipboard

from clipboard

from clipboard

from clipboard

【核心代码】

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
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
List of Tables
Table 3-1: Integer Types in Rust
Table 3-2: Integer Literals in Rust
Table B-1: Operators
Table B-2: Stand-Alone Syntax
Table B-3: Path-Related Syntax
Table B-4: Generics
Table B-5: Trait Bound Constraints
Table B-6: Macros and Attributes
Table B-7: Comments
Table B-8: Tuples
Table B-9: Curly Brackets
Table B-10: Square Brackets
List of Illustrations
Figure 4-1:  Representation in memory of a Stringholding the value "hello"bound to s1
Figure 4-2: Representation in memory of the variable s2that has a copy of the pointer, length, and capacity of s1
Figure 4-3: Another possibility for what s2 = s1might do if Rust copied the heap data as well
Figure 4-4: Representation in memory after s1has been invalidated
Figure 4-5: A diagram of &String spointing at String s1
Figure 4-6: String slice referring to part of a String
Figure 14-1: HTML documentation for the add_onefunction
Figure 14-2: Rendered documentation for my_crate, including the comment describing the crate as a whole
Figure 14-3: Front page of the documentation for artthat lists the kindsand utilsmodules
Figure 14-4: The front page of the documentation for artthat lists the re-exports
Figure 15-1: An infinite Listconsisting of infinite Consvariants
Figure 15-2: A Listthat is not infinitely sized, because Consholds a Box
Figure 15-3: Two lists, band c, sharing ownership of a third list, a
Figure 15-4: A reference cycle of lists aand bpointing to each other
Figure 20-1: Our final shared project
List of Listings
Listing 1-1: A program that prints Hello, world!
Listing 1-2: Contents of Cargo.tomlgenerated by cargo new
Listing 2-1: Code that gets a guess from the user and prints it
Listing 2-2: The output from running cargo buildafter adding the randcrate as a dependency
Listing 2-3: Adding code to generate a random number
Listing 2-4: Handling the possible return values of comparing two numbers
Listing 2-5: Ignoring a non-number guess and asking for another guess instead of crashing the program
Listing 2-6: Complete guessing game code
Listing 3-1: A mainfunction declaration containing one statement
Listing 3-2: Assigning the result of an ifexpression to a variable
Listing 3-3: Using a whileloop to run code while a condition evaluates to true
Listing 3-4: Looping through each element of a collection using a whileloop
Listing 3-5: Looping through each element of a collection using a forloop
Listing 4-1: A variable and the scope in which it is valid
Listing 4-2: Assigning the integer value of variable xto y
Listing 4-3: Functions with ownership and scope annotated
Listing 4-4: Transferring ownership of return values
Listing 4-5: Returning ownership of parameters
Listing 4-6: Attempting to modify a borrowed value
Listing 4-7: The first_wordfunction that returns a byte index value into the Stringparameter
Listing 4-8: Storing the result from calling the first_wordfunction and then changing the Stringcontents
Listing 4-9: Improving the first_wordfunction by using a string slice for the type of the sparameter
Listing 5-1: A Userstruct definition
Listing 5-2: Creating an instance of the Userstruct
Listing 5-3: Changing the value in the emailfield of a Userinstance
Listing 5-4: A build_userfunction that takes an email and username and returns a Userinstance
Listing 5-5: A build_userfunction that uses field init shorthand because the usernameand emailparameters have the same name as struct fields
Listing 5-6: Creating a new Userinstance using one of the values from user1
Listing 5-7: Using struct update syntax to set a new emailvalue for a Userinstance but to use the rest of the values from user1
Listing 5-8: Calculating the area of a rectangle specified by separate width and height variables
Listing 5-9: Specifying the width and height of the rectangle with a tuple
Listing 5-10: Defining a Rectanglestruct
Listing 5-11: Attempting to print a Rectangleinstance
Listing 5-12: Adding the attribute to derive the Debugtrait and printing the Rectangleinstance using debug formatting
Listing 5-13: Defining an areamethod on the Rectanglestruct
Listing 5-14: Using the as-yet-unwritten can_holdmethod
Listing 5-15: Implementing the can_holdmethod on Rectanglethat takes another Rectangleinstance as a parameter
Listing 5-16: Rewriting Listing 5-15 using multiple implblocks
Listing 6-1: Storing the data and IpAddrKindvariant of an IP address using a struct
Listing 6-2: A Messageenum whose variants each store different amounts and types of values
Listing 6-3: An enum and a matchexpression that has the variants of the enum as its patterns
Listing 6-4: A Coinenum in which the Quartervariant also holds a UsStatevalue
Listing 6-5: A function that uses a matchexpression on an Option<i32>
Listing 6-6: A matchthat only cares about executing code when the value is Some
Listing 7-1: A front_of_housemodule containing other modules that then contain functions
Listing 7-2: The module tree for the code in Listing 7-1
Listing 7-3: Calling the add_to_waitlistfunction using absolute and relative paths
Listing 7-4: Compiler errors from building the code in Listing 7-3
Listing 7-5: Declaring the hostingmodule as pubto use it from eat_at_restaurant
Listing 7-6: Compiler errors from building the code in Listing 7-5
Listing 7-7: Adding the pubkeyword to mod hostingand fn add_to_waitlistlets us call the function from eat_at_restaurant
Listing 7-8: Calling a function using a relative path starting with super
Listing 7-9: A struct with some public fields and some private fields
Listing 7-10: Designating an enum as public makes all its variants public.
Listing 7-11: Bringing a module into scope with use
Listing 7-12: A usestatement only applies in the scope it’s in.
Listing 7-13: Bringing the add_to_waitlistfunction into scope with use, which is unidiomatic
Listing 7-14: Bringing HashMapinto scope in an idiomatic way
Listing 7-15: Bringing two types with the same name into the same scope requires using their parent modules.
Listing 7-16: Renaming a type when it’s brought into scope with the askeyword
Listing 7-17: Making a name available for any code to use from a new scope with pub use
Listing 7-18: Specifying a nested path to bring multiple items with the same prefix into scope
Listing 7-19: Two usestatements where one is a subpath of the other
Listing 7-20: Combining the paths in Listing 7-19 into one usestatement
Listing 7-21: Declaring the front_of_housemodule whose body will be in src/front_of_house.rs
Listing 7-22: Definitions inside the front_of_housemodule in src/front_of_house.rs
Listing 8-1: Creating a new, empty vector to hold values of type i32
Listing 8-2: Creating a new vector containing values
Listing 8-3: Using the pushmethod to add values to a vector
Listing 8-4: Using indexing syntax and using the getmethod to access an item in a vector
Listing 8-5: Attempting to access the element at index 100 in a vector containing five elements
Listing 8-6: Attempting to add an element to a vector while holding a reference to an item
Listing 8-7: Printing each element in a vector by iterating over the elements using a forloop
Listing 8-8: Iterating over mutable references to elements in a vector
Listing 8-9: Defining an enum to store values of different types in one vector
Listing 8-10: Showing where the vector and its elements are dropped
Listing 8-11: Creating a new, empty String
Listing 8-12: Using the to_stringmethod to create a Stringfrom a string literal
Listing 8-13: Using the String::fromfunction to create a Stringfrom a string literal
Listing 8-14: Storing greetings in different languages in strings
Listing 8-15: Appending a string slice to a Stringusing the push_strmethod
Listing 8-16: Using a string slice after appending its contents to a String
Listing 8-17: Adding one character to a Stringvalue using push
Listing 8-18: Using the operator to combine two Stringvalues into a new Stringvalue
Listing 8-19: Attempting to use indexing syntax with a String
Listing 8-20: Creating a new hash map and inserting some keys and values
Listing 8-21: Accessing the score for the Blue team stored in the hash map
Listing 8-22: Showing that keys and values are owned by the hash map once they’re inserted
Listing 8-23: Replacing a value stored with a particular key
Listing 8-24: Using the entrymethod to only insert if the key does not already have a value
Listing 8-25: Counting occurrences of words using a hash map that stores words and counts
Listing 9-1: Attempting to access an element beyond the end of a vector, which will cause a call to panic!
Listing 9-2: The backtrace generated by a call to panic!displayed when the environment variable RUST_BACKTRACEis set
Listing 9-3: Opening a file
Listing 9-4: Using a matchexpression to handle the Resultvariants that might be returned
Listing 9-5: Handling different kinds of errors in different ways
Listing 9-6: A function that returns errors to the calling code using match
Listing 9-7: A function that returns errors to the calling code using the ?operator
Listing 9-8: Chaining method calls after the ?operator
Listing 9-9: Using fs::read_to_stringinstead of opening and then reading the file
Listing 9-10: Attempting to use the ?in the mainfunction that returns ()won’t compile.
Listing 9-11: Using the ?operator on an Option<T>value
Listing 9-12: Changing mainto return Result<(), E>allows the use of the ?operator on Resultvalues.
Listing 9-13: A Guesstype that will only continue with values between 1 and 100
Listing 10-1: Finding the largest number in a list of numbers
Listing 10-2: Code to find the largest number in twolists of numbers
Listing 10-3: Abstracted code to find the largest number in two lists
Listing 10-4: Two functions that differ only in their names and in the types in their signatures
Listing 10-5: The largestfunction using generic type parameters; this doesn’t compile yet
Listing 10-6: A Point<T>struct that holds xand yvalues of type T
Listing 10-7: The fields xand ymust be the same type because both have the same generic data typeT
Listing 10-8: A Point<T, U>generic over two types so that xand ycan be values of different types
Listing 10-9: Implementing a method named xon the Point<T>struct that will return a reference to the xfield of type T
Listing 10-10: An implblock that only applies to a struct with a particular concrete type for the generic type parameter T
Listing 10-11: A method that uses generic types different from its struct’s definition
Listing 10-12: A Summarytrait that consists of the behavior provided by a summarizemethod
Listing 10-13: Implementing the Summarytrait on the NewsArticleand Tweettypes
Listing 10-14: Defining a Summarytrait with a default implementation of the summarizemethod
Listing 10-15: Conditionally implementing methods on a generic type depending on trait bounds
Listing 10-16: An attempt to use a reference whose value has gone out of scope
Listing 10-17: Annotations of the lifetimes of rand x, named 'aand 'b, respectively
Listing 10-18: A valid reference because the data has a longer lifetime than the reference
Listing 10-19: A mainfunction that calls the longestfunction to find the longer of two string slices
Listing 10-20: An implementation of the longestfunction that returns the longer of two string slices but does not yet compile
Listing 10-21: The longestfunction definition specifying that all the references in the signature must have the same lifetime 'a
Listing 10-22: Using the longestfunction with references to Stringvalues that have different concrete lifetimes
Listing 10-23: Attempting to use resultafter string2has gone out of scope
Listing 10-24: A struct that holds a reference, requiring a lifetime annotation
Listing 10-25: A function we defined in Listing 4-9 that compiled without lifetime annotations, even though the parameter and return type are references
Listing 11-1: The test module and function generated automatically by cargo new
Listing 11-2: The output from running the automatically generated test
Listing 11-3: Adding a second test that will fail because we call the panic!macro
Listing 11-4: Test results when one test passes and one test fails
Listing 11-5: Using the Rectanglestruct and its can_holdmethod from Chapter 5
Listing 11-6: A test for can_holdthat checks whether a larger rectangle can indeed hold a smaller rectangle
Listing 11-7: Testing the function add_twousing the assert_eq!macro
Listing 11-8: Testing that a condition will cause a panic!
Listing 11-9: Testing for a panic!with a panic message containing a specified substring
Listing 11-10: Tests for a function that calls println!
Listing 11-11: Three tests with three different names
Listing 11-12: Testing a private function
Listing 11-13: An integration test of a function in the addercrate
Listing 12-1: Collecting the command line arguments into a vector and printing them
Listing 12-2: Creating variables to hold the query argument and file path argument
Listing 12-3: A poem by Emily Dickinson makes a good test case.
Listing 12-4: Reading the contents of the file specified by the second argument
Listing 12-5: Extracting a parse_configfunction from main
Listing 12-6: Refactoring parse_configto return an instance of a Configstruct
Listing 12-7: Changing parse_configinto Config::new
Listing 12-8: Adding a check for the number of arguments
Listing 12-9: Returning a Resultfrom Config::build
Listing 12-10: Exiting with an error code if building a Configfails
Listing 12-11: Extracting a runfunction containing the rest of the program logic
Listing 12-12: Changing the runfunction to return Result
Listing 12-13: Moving Configand runinto src/lib.rs
Listing 12-14: Using the minigreplibrary crate in src/main.rs
Listing 12-15: Creating a failing test for the searchfunction we wish we had
Listing 12-16: Defining just enough of the searchfunction so our test will compile
Listing 12-17: Iterating through each line in contents
Listing 12-18: Adding functionality to see whether the line contains the string in query
Listing 12-19: Storing the lines that match so we can return them
Listing 12-20: Adding a new failing test for the case-insensitive function we’re about to add
Listing 12-21: Defining the search_case_insensitivefunction to lowercase the query and the line before comparing them
Listing 12-22: Calling either searchor search_case_insensitivebased on the value in config.ignore_case
Listing 12-23: Checking for any value in an environment variable named IGNORE_CASE
Listing 12-24: Writing error messages to standard error instead of standard output using eprintln!
Listing 13-1: Shirt company giveaway situation
Listing 13-2: Adding optional type annotations of the parameter and return value types in the closure
Listing 13-3: Attempting to call a closure whose types are inferred with two different types
Listing 13-4: Defining and calling a closure that captures an immutable reference
Listing 13-5: Defining and calling a closure that captures a mutable reference
Listing 13-6: Using moveto force the closure for the thread to take ownership of list
Listing 13-7: Using sort_by_keyto order rectangles by width
Listing 13-8: Attempting to use an FnOnceclosure with sort_by_key
Listing 13-9: Using an FnMutclosure with sort_by_keyis allowed.
Listing 13-10: Creating an iterator
Listing 13-11: Using an iterator in a forloop
Listing 13-12: Calling the nextmethod on an iterator
Listing 13-13: Calling the summethod to get the total of all items in the iterator
Listing 13-14: Calling the iterator adapter mapto create a new iterator
Listing 13-15: Calling the mapmethod to create a new iterator, and then calling the collectmethod to consume the new iterator and create a vector
Listing 13-16: Using the filtermethod with a closure that captures shoe_size
Listing 13-17: Reproduction of the Config::buildfunction from Listing 12-23
Listing 13-18: Passing the return value of env::argsto Config::build
Listing 13-19: Updating the signature of Config::buildto expect an iterator
Listing 13-20: Changing the body of Config::buildto use iterator methods
Listing 13-21: The implementation of the searchfunction from Listing 12-19
Listing 13-22: Using iterator adapter methods in the implementation of the searchfunction
Listing 14-1: A documentation comment for a function
Listing 14-2: Documentation for the my_cratecrate as a whole
Listing 14-3: An artlibrary with items organized into kindsand utilsmodules
Listing 14-4: A crate using the artcrate’s items with its internal structure exported
Listing 14-5: Adding pub usestatements to re-export items
Listing 14-6: A program using the re-exported items from the artcrate
Listing 14-7: Using the add_onelibrary crate from the addercrate
Listing 15-1: Storing an i32value on the heap using a box
Listing 15-2: The first attempt at defining an enum to represent a cons list data structure of i32values
Listing 15-3: Using the Listenum to store the list 1, 2, 3
Listing 15-4: The error we get when attempting to define a recursive enum
Listing 15-5: Definition of Listthat uses Box<T>in order to have a known size
Listing 15-6: Using the dereference operator to follow a reference to an i32value
Listing 15-7: Using the dereference operator on a Box<i32>
Listing 15-8: Defining a MyBox<T>type
Listing 15-9: Attempting to use MyBox<T>in the same way we used references and Box<T>
Listing 15-10: Implementing Derefon MyBox<T>
Listing 15-11: A hellofunction that has the parameter nameof type &str
Listing 15-12: Calling hellowith a reference to a MyBox<String>value, which works because of deref coercion
Listing 15-13: The code we would have to write if Rust didn’t have deref coercion
Listing 15-14: A CustomSmartPointerstruct that implements the Droptrait where we would put our cleanup code
Listing 15-15: Attempting to call the dropmethod from the Droptrait manually to clean up early
Listing 15-16: Calling std::mem::dropto explicitly drop a value before it goes out of scope
Listing 15-17: Demonstrating that we’re not allowed to have two lists using Box<T>that try to share ownership of a third list
Listing 15-18: A definition of Listthat uses Rc<T>
Listing 15-19: Printing the reference count
Listing 15-20: A library to keep track of how close a value is to a maximum value and warn when the value is at certain levels
Listing 15-21: An attempt to implement a MockMessengerthat isn’t allowed by the borrow checker
Listing 15-22: Using RefCell<T>to mutate an inner value while the outer value is considered immutable
Listing 15-23: Creating two mutable references in the same scope to see that RefCell<T>will panic
Listing 15-24: Using Rc<RefCell<i32>>to create a Listthat we can mutate
Listing 15-25: A cons list definition that holds a RefCell<T>so we can modify what a Consvariant is referring to
Listing 15-26: Creating a reference cycle of two Listvalues pointing to each other
Listing 15-27: Creating a leafnode with no children and a branchnode with leafas one of its children
Listing 15-28: A leafnode with a weak reference to its parent node, branch
Listing 15-29: Creating branchin an inner scope and examining strong and weak reference counts
Listing 16-1: Creating a new thread to print one thing while the main thread prints something else
Listing 16-2: Saving a JoinHandle<T>from thread::spawnto guarantee the thread is run to completion
Listing 16-3: Attempting to use a vector created by the main thread in another thread
Listing 16-4: A thread with a closure that attempts to capture a reference to vfrom a main thread that drops v
Listing 16-5: Using the movekeyword to force a closure to take ownership of the values it uses
Listing 16-6: Creating a channel and assigning the two halves to txand rx
Listing 16-7: Moving txto a spawned thread and sending "hi"
Listing 16-8: Receiving the value "hi"in the main thread and printing it
Listing 16-9: Attempting to use valafter we’ve sent it down the channel
Listing 16-10: Sending multiple messages and pausing between each one
Listing 16-11: Sending multiple messages from multiple producers
Listing 16-12: Exploring the API of Mutex<T>in a single-threaded context for simplicity
Listing 16-13: Ten threads, each incrementing a counter guarded by a Mutex<T>
Listing 16-14: Attempting to use Rc<T>to allow multiple threads to own the Mutex<T>
Listing 16-15: Using an Arc<T>to wrap the Mutex<T>to be able to share ownership across multiple threads
Listing 17-1: An AveragedCollectionstruct that maintains a list of integers and the average of the items in the collection
Listing 17-2: Implementations of the public methods add, remove, and averageon AveragedCollection
Listing 17-3: Definition of the Drawtrait
Listing 17-4: Definition of the Screenstruct with a componentsfield holding a vector of trait objects that implement the Drawtrait
Listing 17-5: A runmethod on Screenthat calls the drawmethod on each component
Listing 17-6: An alternate implementation of the Screenstruct and its runmethod using generics and trait bounds
Listing 17-7: A Buttonstruct that implements the Drawtrait
Listing 17-8: Another crate using guiand implementing the Drawtrait on a SelectBoxstruct
Listing 17-9: Using trait objects to store values of different types that implement the same trait
Listing 17-10: Attempting to use a type that doesn’t implement the trait object’s trait
Listing 17-11: Code that demonstrates the desired behavior we want our blogcrate to have
Listing 17-12: Definition of a Poststruct and a newfunction that creates a new Postinstance, a Statetrait, and a Draftstruct
Listing 17-13: Implementing the add_textmethod to add text to a post’s content
Listing 17-14: Adding a placeholder implementation for the contentmethod on Postthat always returns an empty string slice
Listing 17-15: Implementing request_reviewmethods on Postand the Statetrait
Listing 17-16: Implementing the approvemethod on Postand the Statetrait
Listing 17-17: Updating the contentmethod on Postto delegate to a contentmethod on State
Listing 17-18: Adding the contentmethod to the Statetrait
Listing 17-19: A Postwith a contentmethod and a DraftPostwithout a contentmethod
Listing 17-20: A PendingReviewPostthat gets created by calling request_reviewon DraftPostand an approvemethod that turns a PendingReviewPostinto a published Post
Listing 17-21: Modifications to mainto use the new implementation of the blog post workflow
Listing 18-1: Mixing if let, else if, else if let, and else
Listing 18-2: Using a while letloop to print values for as long as stack.pop()returns Some
Listing 18-3: Using a pattern in a forloop to destructure a tuple
Listing 18-4: Using a pattern to destructure a tuple and create three variables at once
Listing 18-5: Incorrectly constructing a pattern whose variables don’t match the number of elements in the tuple
Listing 18-6: A function signature using patterns in the parameters
Listing 18-7: A function with parameters that destructure a tuple
Listing 18-8: Attempting to use a refutable pattern with let
Listing 18-9: Using if letand a block with refutable patterns instead of let
Listing 18-10: Attempting to use an irrefutable pattern with if let
Listing 18-11: A matchexpression with an arm that introduces a shadowed variable y
Listing 18-12: Destructuring a struct’s fields into separate variables
Listing 18-13: Destructuring struct fields using struct field shorthand
Listing 18-14: Destructuring and matching literal values in one pattern
Listing 18-15: Destructuring enum variants that hold different kinds of values
Listing 18-16: Matching on nested enums
Listing 18-17: Using _in a function signature
Listing 18-18: Using an underscore within patterns that match Somevariants when we don’t need to use the value inside the Some
Listing 18-19: Ignoring multiple parts of a tuple
Listing 18-20: Starting a variable name with an underscore to avoid getting unused variable warnings
Listing 18-21: An unused variable starting with an underscore still binds the value, which might take ownership of the value.
Listing 18-22: Using an underscore does not bind the value.
Listing 18-23: Ignoring all fields of a Pointexcept for xby using 
Listing 18-24: Matching only the first and last values in a tuple and ignoring all other values
Listing 18-25: An attempt to use in an ambiguous way
Listing 18-26: Adding a match guard to a pattern
Listing 18-27: Using a match guard to test for equality with an outer variable
Listing 18-28: Combining multiple patterns with a match guard
Listing 18-29: Using @to bind to a value in a pattern while also testing it
Listing 19-1: Creating raw pointers from references
Listing 19-2: Creating a raw pointer to an arbitrary memory address
Listing 19-3: Dereferencing raw pointers within an unsafeblock
Listing 19-4: Using the safe split_at_mutfunction
Listing 19-5: An attempted implementation of split_at_mutusing only safe Rust
Listing 19-6: Using unsafe code in the implementation of the split_at_mutfunction
Listing 19-7: Creating a slice from an arbitrary memory location
Listing 19-8: Declaring and calling an externfunction defined in another language
Listing 19-9: Defining and using an immutable static variable
Listing 19-10: Reading from or writing to a mutable static variable is unsafe.
Listing 19-11: Defining and implementing an unsafe trait
Listing 19-12: The definition of the Iteratortrait that has an associated type Item
Listing 19-13: A hypothetical definition of the Iteratortrait using generics
Listing 19-14: Implementing the Addtrait to overload the operator for Pointinstances
Listing 19-15: Implementing the Addtrait on Millimetersto add Millimetersand Meters
Listing 19-16: Two traits are defined to have a flymethod and are implemented on the Humantype, and a flymethod is implemented on Humandirectly.
Listing 19-17: Calling flyon an instance of Human
Listing 19-18: Specifying which trait’s flymethod we want to call
Listing 19-19: A trait with an associated function and a type with an associated function of the same name that also implements the trait
Listing 19-20: Attempting to call the baby_namefunction from the Animaltrait, but Rust doesn’t know which implementation to use
Listing 19-21: Using fully qualified syntax to specify that we want to call the baby_namefunction from the Animaltrait as implemented on Dog
Listing 19-22: Implementing the OutlinePrinttrait that requires the functionality from Display
Listing 19-23: Creating a Wrappertype around Vec<String>to implement Display
Listing 19-24: Using a long type in many places
Listing 19-25: Introducing a type alias, Thunk, to reduce repetition
Listing 19-26: A matchwith an arm that ends in continue
Listing 19-27: Using the fntype to accept a function pointer as an argument
Listing 19-28: A simplified version of the vec!macro definition
Listing 19-29: An example of defining a procedural macro
Listing 19-30: The code a user of our crate will be able to write when using our procedural macro
Listing 19-31: Code that most procedural macro crates will require in order to process Rust code
Listing 19-32: The DeriveInputinstance we get when parsing the code that has the macro’s attribute in Listing 19-30
Listing 19-33: Implementing the HelloMacrotrait using the parsed Rust code
Listing 20-1: Listening for incoming streams and printing a message when we receive a stream
Listing 20-2: Reading from the TcpStreamand printing the data
Listing 20-3: Writing a tiny successful HTTP response to the stream
Listing 20-4: A sample HTML file to return in a response
Listing 20-5: Sending the contents of hello.xhtmlas the body of the response
Listing 20-6: Handling requests to /differently from other requests
Listing 20-7: Responding with status code 404 and an error page if anything other than /was requested
Listing 20-8: Sample content for the page to send back with any 404 response
Listing 20-9: Refactoring the ifand elseblocks to contain only the code that differs between the two cases
Listing 20-10: Simulating a slow request by sleeping for five seconds
Listing 20-11: Spawning a new thread for each stream
Listing 20-12: Our ideal ThreadPoolinterface
Listing 20-13: Implementing ThreadPool::newto panic if sizeis zero
Listing 20-14: Creating a vector for ThreadPoolto hold the threads
Listing 20-15: Modifying ThreadPoolto hold Workerinstances instead of holding threads directly
Listing 20-16: Modifying ThreadPoolto store the sender of a channel that transmits Jobinstances
Listing 20-17: Passing the receiver to each Worker
Listing 20-18: Sharing the receiver among the Workerinstances using Arcand Mutex
Listing 20-19: Creating a Jobtype alias for a Boxthat holds each closure and then sending the job down the channel
Listing 20-20: Receiving and executing the jobs in the Workerinstance’s thread
Listing 20-21: An alternative implementation of Worker::newusing while let
Listing 20-22: Joining each thread when the thread pool goes out of scope
Listing 20-23: Explicitly dropping senderbefore joining the Workerthreads
Listing 20-24: Explicitly breaking out of the loop when recvreturns an error
Listing 20-25: Shutting down the server after serving two requests by exiting the loop
Guide
Cover
Front Matter
Foreword
Preface
Introduction
Chapter 1: Getting Started
Start Reading
Chapter 2: Programming a Guessing Game
Chapter 3: Common Programming Concepts
Chapter 4: Understanding Ownership
Chapter 5: Using Structs to Structure Related Data
Chapter 6: Enums and Pattern Matching
Chapter 7: Managing Growing Projects with Packages, Crates, and Modules
Chapter 8: Common Collections
Chapter 9: Error Handling
Chapter 10: Generic Types, Traits, and Lifetimes
Chapter 11: Writing Automated Tests
Chapter 12: An I/O Project: Building a Command Line Program
Chapter 13: Functional Language Features: Iterators and Closures
Chapter 14: More About Cargo and Crates.io
Chapter 15: Smart Pointers
Chapter 16: Fearless Concurrency
Chapter 17: Object-Oriented Programming Features
Chapter 18: Patterns and Matching
Chapter 19: Advanced Features
Chapter 20: Final Project: Building a Multithreaded Web Server
Appendix A: Keywords
Appendix B: Operators and Symbols
Appendix C: Derivable Traits
Appendix D: Useful Development Tools
Appendix E: Editions



实例下载地址

rust编程语言_The.Rust.Programming.Language.2nd.Edition.2022.12

不能下载?内容有错? 点击这里报错 + 投诉 + 提问

好例子网口号:伸出你的我的手 — 分享

网友评论

发表评论

(您的评论需要经过审核才能显示)

查看所有0条评论>>

小贴士

感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。

  • 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
  • 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
  • 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
  • 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。

关于好例子网

本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明

;
报警