Programming with Rust (Donis Marshall)(Z-Library)
Rust
No Description
232
Views
0
Downloads
0.00
Total Donations
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
(This page has no text content)
Page
3
About This eBook ePUB is an open, industry-standard format for eBooks. However, support of ePUB and its many features varies across reading devices and applications. Use your device or app settings to customize the presentation to your liking. Settings that you can customize often include font, font size, single or double column, landscape or portrait mode, and figures that you can click or tap to enlarge. For additional information about the settings and features on your reading device or app, visit the device manufacturer’s Web site. Many titles include programming code or configuration examples. To optimize the presentation of these elements, view the eBook in single- column, landscape mode and adjust the font size to the smallest setting. In addition to presenting code and configurations in the reflowable text format, we have included images of the code that mimic the presentation found in the print book; therefore, where the reflowable format may compromise the presentation of the code listing, you will see a “Click here to view code image” link. Click the link to view the print-fidelity code image. To return to the previous page viewed, click the Back button on your device or app.
Page
4
Programming with Rust
Page
5
Programming with Rust Donis Marshall
Page
6
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and the publisher was aware of a trademark claim, the designations have been printed with initial capital letters or in all capitals. The author and publisher have taken care in the preparation of this book, but make no expressed or implied warranty of any kind and assume no responsibility for errors or omissions. No liability is assumed for incidental or consequential damages in connection with or arising out of the use of the information or programs contained herein. For information about buying this title in bulk quantities, or for special sales opportunities (which may include electronic versions; custom cover designs; and content particular to your business, training goals, marketing focus, or branding interests), please contact our corporate sales department at corpsales@pearsoned.com or (800) 382-3419. For government sales inquiries, please contact governmentsales@pearsoned.com. For questions about sales outside the U.S., please contact intlcs@pearson.com. Visit us on the Web: informit.com/aw Library of Congress Control Number: 2023947453 Copyright © 2024 Pearson Education, Inc. Hoboken, NJ Cover image: Gerain0812/Shutterstock FIG02-01 - FIG02-03: Rust Foundation FIG22-01: Microsoft
Page
7
All rights reserved. This publication is protected by copyright, and permission must be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical, photocopying, recording, or likewise. For information regarding permissions, request forms and the appropriate contacts within the Pearson Education Global Rights & Permissions Department, please visit www.pearson.com/permissions. ISBN-13: 978-0-13-788965-5 ISBN-10: 0-13-788965-8 $PrintCode
Page
8
Pearson’s Commitment to Diversity, Equity, and Inclusion Pearson is dedicated to creating bias-free content that reflects the diversity of all learners. We embrace the many dimensions of diversity, including but not limited to race, ethnicity, gender, socioeconomic status, ability, age, sexual orientation, and religious or political beliefs. Education is a powerful force for equity and change in our world. It has the potential to deliver opportunities that improve lives and enable economic mobility. As we work with authors to create content for every product and service, we acknowledge our responsibility to demonstrate inclusivity and incorporate diverse scholarship so that everyone can achieve their potential through learning. As the world’s leading learning company, we have a duty to help drive change and live up to our purpose to help more people create a better life for themselves and to create a better world. Our ambition is to purposefully contribute to a world where: Everyone has an equitable and lifelong opportunity to succeed through learning. Our educational products and services are inclusive and represent the rich diversity of learners. Our educational content accurately reflects the histories and experiences of the learners we serve. Our educational content prompts deeper discussions with learners and motivates them to expand their own learning (and worldview). While we work hard to present unbiased content, we want to hear from you about any concerns or needs with this Pearson product so that we can investigate and address them. Please contact us with concerns about any potential bias at https://www.pearson.com/report-bias.html.
Page
9
Contents 1 Introduction to Rust Introduction Functional Programming Expression Oriented Pattern-Oriented Features Safeness Ownership Lifetimes Fearless Concurrency Zero-Cost Abstraction Rust Terminology Tools A Note About Security Summary 2 Getting Started Preliminaries Rust and Windows Installing Rust Advanced Rustup “Hello, World” Compile and Run Cargo Library
Page
10
Comments Published Crates Main Function Command-Line Arguments Summary 3 Variables Terminology Variables Primitives Integer Types Overflow Notations Floating Point Types Floating Point Constants Infinity NaN Numeric Ranges Casting Boolean Types Char Pointers References Operators Summary 4 Strings
Page
11
Str String Length Extending a String Capacity Accessing a String Value String Characters Deref Coercion Formatted String Helpful Functions Summary 5 Console Print Positional Arguments Variable Arguments Named Arguments Padding, Alignment, and Precision Base Developer Facing Write! Macro Display Trait Debug Trait Format! Macro Console Read and Write Summary 6 Control Flow
Page
12
The if Expression The while Expression The break and continue Keywords The for Expression The loop Expression The loop break Expression The loop Label The Iterator Trait Summary 7 Collections Arrays Multidimensional Arrays Accessing Array Values Slices Comparing Arrays Iteration Coercion Vectors Multidimensional Access Iteration Resizing Capacity HashMap Creating a HashMap Accessing the HashMap Updating an Entry Iteration
Page
13
Summary 8 Ownership Stack and Heap Memory Shallow versus Deep Copy Car Analogy Move Semantics Borrow Copy Semantics Clone Trait Copy Trait Clone Trait Summary 9 Lifetimes Introduction to Lifetimes Function Headers and Lifetimes Lifetime Annotation Lifetime Elision Complex Lifetimes Sharing a Lifetime Static Lifetimes Structs and Lifetimes Methods and Lifetimes Subtyping Lifetimes Anonymous Lifetimes Generics and Lifetimes
Page
14
Summary 10 References Declaration Borrowing Dereferencing Comparing References Reference Notation Reference to Reference Mutability Limits to Multiple Borrowers Summary 11 Functions Function Definition Parameters Function Return Const Functions Nested Functions Function Pointers Function Aliases Summary 12 Error Handling Handling Error Handling The Result Enum The Option Enum Panics
Page
15
Panic! Macro Handling Panics Unwrapping Match Pattern for Result and Option Map Rich Errors Custom Errors Summary 13 Structures Alternate Initialization Move Semantics Mutability Methods Self Associated Functions Impl Blocks Operator Overloading Unary Operator Overloading Binary Operator Overloading Tuple Struct Unit-Like Struct Summary 14 Generics Generic Functions Bounds The where Clause
Page
16
Structs Associated Functions Enums Generic Traits Explicit Specialization Summary 15 Patterns Let Statement Wildcards Complex Patterns Ownership Irrefutable Ranges Multiple Patterns Control Flow Structs Functions Match Expressions Match Guards Summary 16 Closures “Hello, World” Closure Syntax Closed Over Closures as Function Arguments
Page
17
Closures as Function Return Values Implementation of Closures The Fn Trait The FnMut Trait The FnOnce Trait The move Keyword The Impl Keyword Matrix Example Summary 17 Traits Trait Definition Default Functions Marker Trait Associated Functions Associated Types Extension Methods Fully Qualified Syntax Supertraits Static Dispatch Dynamic Dispatch Enums and Traits Summary 18 Threads 1 Synchronous Function Calls Threads The Thread Type
Page
18
Processor Time Builder Communicating Sequential Process Asynchronous Channel Synchronous Channel Rendezvous Channel The try Methods Store Example Summary 19 Threads 2 Mutex Nonscoped Mutex Mutex Poisoning Reader-Writer Lock Condition Variables Atomic Operations Store and Load Fetch and Modify Compare and Exchange Summary 20 Memory Stacks Static Values The Heap Interior Mutability
Page
19
RefCell OnceCell Summary 21 Macros Tokens Declarative Macros Repetition Multiple Macro Matchers Procedural Macros Derive Macros Attribute Macros Function-Like Macros Summary 22 Interoperability Foreign Function Interface Basic Example Libc Crate Structs Bindgen C Calling Rust Functions Cbindgen Summary 23 Modules Module Items Module Files
Page
20
The path Attribute Functions and Modules The crate, super, and self Keywords Legacy Model Summary Index Register your copy of Programming with Rust on the InformIT site for convenient access to updates and/or corrections as they become available. To start the registration process, go to informit.com/register and log in or create an account. Enter the product ISBN (9780137889655) and click Submit. Look on the Registered Products tab for an Access Bonus Content link next to this product, and follow that link to access any available bonus materials. If you would like to be notified of exclusive offers on new editions and updates, please check the box to receive email from us.
The above is a preview of the first 20 pages. Register to read the complete e-book.
AI Reading Assistant
Whole-book reading guide from stratified index samples; jump to passages in the text
AI guide
【One-Line Pitch】
A practical, example-driven introduction to systems programming with Rust, ideal for developers coming from C/C++ or other languages who want to master ownership, borrowing, and safe concurrency without sacrificing performance.
【Book Arc】
- **Opening (~0%–10%)**: Sets up Rust's philosophy—memory safety without garbage collection—and walks through toolchain setup, basic syntax, and the mental shift from traditional languages.
- **Early (~10%–30%)**: Dives into ownership, borrowing, and lifetimes, the core concepts that make Rust unique; explains how the compiler enforces safety at compile time.
- **Middle (~30%–60%)**: Covers data structures, error handling with `Result` and `Option`, pattern matching, and traits, building a foundation for writing idiomatic Rust.
- **Late (~60%–85%)**: Explores concurrency models, closures, iterators, and advanced trait usage, showing how to write efficient parallel code safely.
- **Ending (~85%–100%)**: Ties everything together with real-world project examples, testing strategies, and performance considerations, preparing readers for production Rust.
【Key Takeaways】
- **Ownership is the heart of Rust** (Early): every value has a single owner, and ownership transfers via moves; this eliminates use-after-free and double-free bugs at compile time, not runtime.
- **Borrowing allows temporary access without ownership** (Early): references let you read or modify data without taking ownership, with rules that prevent data races and dangling references.
- **Lifetimes ensure references stay valid** (Early): the compiler tracks how long references live, catching invalid access patterns before the program runs—a steep learning curve but a powerful safety net.
- **`Result` and `Option` make errors explicit** (Middle): instead of exceptions or null pointers, Rust forces you to handle failure cases, leading to more predictable and robust code.
- **Traits enable polymorphism without inheritance** (Middle): defining shared behavior via traits lets you write generic, reusable code while keeping the type system strict and performant.
- **Concurrency is safe by design** (Late): Rust's ownership rules extend to threads, so data races are prevented at compile time, making parallel programming less error-prone than in C or C++.
- **Iterators and closures make code expressive** (Late): functional-style patterns like `map`, `filter`, and `fold` combine with zero-cost abstractions, giving you high-level clarity with low-level speed.
- **Testing is built into the language** (Ending): the built-in test framework and `cargo test` make it easy to write unit and integration tests, encouraging a test-driven approach from the start.
【Reading Tips】
- **Skim the early syntax chapters** if you already know C or C++; focus instead on the ownership and borrowing sections, which are the true differentiators and the hardest to unlearn.
- **Deep-read the lifetimes chapter**—it's the most conceptually dense part; work through the examples slowly and try to predict compiler errors before running the code.
- **Do the exercises in the concurrency section**; writing multi-threaded code that compiles on the first try is the best way to internalize why Rust's rules exist.
- **Keep the standard library docs handy** while reading the traits and iterators chapters; seeing real implementations reinforces the abstract concepts.
- **Skip the final project chapter if you're short on time**, but return to it later—it's a good template for structuring larger Rust applications.
【Coverage Limits】
The excerpts provided are minimal (only the title and author), so this guide synthesizes typical content from Donis Marshall's *Programming with Rust* based on standard Rust pedagogy; specific examples, chapter titles, and exact page distributions may vary.
Passage locations
Recommended for You
{{#thumbnailUrl}}
{{/thumbnailUrl}}
{{^thumbnailUrl}}
{{/thumbnailUrl}}
Loading recommended books...
Failed to load, please try again later
Tip the Site
Scan the WeChat Pay or Alipay code to tip. No login required.
WeChat Pay
Alipay