Code Like a Pro in Rust (Brenden Matthews) (Z-Library)

Author: Brenden Matthews

商业

Get ready to code like a pro in Rust with insider techniques used by Rust veterans! Code Like a Pro in Rust dives deep into memory management, asynchronous programming, and the core Rust skills that make you a Rust pro! Plus, you’ll find essential productivity techniques for Rust testing, tooling, and project management. You’ll soon be writing high-quality code that needs way less maintenance overhead. In Code Like A Pro in Rust, you will learn: Essential Rust tooling Core Rust data structures Memory management Testing in Rust Asynchronous programming for Rust Optimized Rust Rust project management Code Like A Pro in Rust is a fast-track guide to building and delivering professional quality software in Rust. It skips the fluff and gets right to the heart of this powerful modern language. You’ll learn how to sidestep common Rust pitfalls and navigate quirks you might never have seen before—even if you’ve been programming for many years! Plus, discover timeless strategies for navigating the evolving Rust ecosystem and ensure your skills can easily adapt to future changes. About the technology Rust is famous for its safety, performance, and security, but it takes pro skills to make this powerful language shine. This book gets you up to speed fast, so you’ll feel confident with low-level systems, web applications, asynchronous programming, concurrency, optimizations, and much more. About the book Code Like a Pro in Rust will make you a more productive Rust programmer. This example-rich book builds on your existing know-how by introducing Rust-specific design patterns, coding shortcuts, and veteran skills like asynchronous programming and integrating Rust with other languages. You’ll also meet amazing Rust tools for testing, code analysis, and application lifecycle management. It’s all the good stuff in one place!

📄 File Format: PDF
💾 File Size: 10.9 MB
19
Views
0
Downloads
0.00
Total Donations

📄 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
M A N N I N G Brenden Matthews
📄 Page 2
Machine languages Low level High level Scripting languages: Python, Ruby, and Elixir High-level languages Domain-specific languages Esoteric languages Rust sweet spot Assembly languages System languages: C, C++, C#, Java, Go, and Rust
📄 Page 3
Code Like a Pro in Rust BRENDEN MATTHEWS M A N N I N G SHELTER ISLAND
📄 Page 4
For online information and ordering of this and other Manning books, please visit www.manning.com. The publisher offers discounts on this book when ordered in quantity. For more information, please contact Special Sales Department Manning Publications Co. 20 Baldwin Road PO Box 761 Shelter Island, NY 11964 Email: orders@manning.com ©2024 by Manning Publications Co. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps. Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid-free paper, and we exert our best efforts to that end. Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15 percent recycled and processed without the use of elemental chlorine. The author and publisher have made every effort to ensure that the information in this book was correct at press time. The author and publisher do not assume and hereby disclaim any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from negligence, accident, or any other cause, or from any usage of the information herein. Manning Publications Co. Development editor: Karen Miller 20 Baldwin Road Review editor: Aleksandar Dragosavljević PO Box 761 Production editor: Deirdre Hiam Shelter Island, NY 11964 Copy editor: Christian Berk Proofreader: Katie Tennant Technical proofreader: Jonathan Reeves Typesetter: Gordan Salinovic Cover designer: Marija Tudor ISBN 9781617299643 Printed in the United States of America
📄 Page 5
iii brief contents 1 ■ Feelin’ Rusty 1 PART 1 PRO RUST.......................................................................9 2 ■ Project management with Cargo 11 3 ■ Rust tooling 43 PART 2 CORE DATA ...................................................................63 4 ■ Data structures 65 5 ■ Working with memory 93 PART 3 CORRECTNESS..............................................................119 6 ■ Unit testing 121 7 ■ Integration testing 141 PART 4 ASYNCHRONOUS RUST ..................................................155 8 ■ Async Rust 157 9 ■ Building an HTTP REST API service 182 10 ■ Building an HTTP REST API CLI 204 PART 5 OPTIMIZATIONS............................................................217 11 ■ Optimizations 219
📄 Page 6
iv contents preface x acknowledgments xi about this book xii about the author xvi about the cover illustration xvii 1 Feelin’ Rusty 1 1.1 What’s Rust? 2 1.2 What’s unique about Rust? 4 Rust is safe 4 ■ Rust is modern 5 ■ Rust is pure open source 5 Rust vs. other popular languages 6 1.3 When should you use Rust? 7 Rust use cases 7 1.4 Tools you’ll need 8 PART 1 PRO RUST............................................................ 9 2 Project management with Cargo 11 2.1 Cargo tour 12 Basic usage 12 ■ Creating a new application or library 13 Building, running, and testing 14 ■ Switching between toolchains 15
📄 Page 7
CONTENTS v 2.2 Dependency management 16 Handling the Cargo.lock file 18 2.3 Feature flags 19 2.4 Patching dependencies 21 Indirect dependencies 23 ■ Best practices for dependency patching 23 2.5 Publishing crates 24 CI/CD integration 24 2.6 Linking to C libraries 27 2.7 Binary distribution 29 Cross compilation 30 ■ Building statically linked binaries 30 2.8 Documenting Rust projects 31 Code examples in documentation 34 2.9 Modules 35 2.10 Workspaces 37 2.11 Custom building scripts 40 2.12 Rust projects in embedded environments 41 Memory allocation 42 3 Rust tooling 43 3.1 Overview of Rust tooling 44 3.2 Using rust-analyzer for Rust IDE integration 45 Magic completions 46 3.3 Using rustfmt to keep code tidy 49 Installing rustfmt 50 ■ Configuring rustfmt 50 3.4 Using Clippy to improve code quality 51 Installing Clippy 51 ■ Clippy’s lints 52 ■ Configuring Clippy 53 ■ Automatically applying Clippy’s suggestions 54 Using Clippy in CI/CD 54 3.5 Reducing compile times with sccache 55 Installing sccache 55 ■ Configuring sccache 56 3.6 Integration with IDEs, including Visual Studio Code 56 3.7 Using toolchains: Stable vs. nightly 57 Nightly-only features 57 ■ Using nightly on published crates 58
📄 Page 8
CONTENTSvi 3.8 Additional tools: cargo-update, cargo-expand, cargo-fuzz, cargo-watch, cargo-tree 58 Keeping packages up to date date with cargo-update 59 Debugging macros with cargo-expand 59 ■ Testing libFuzzer 60 Iterating with cargo-watch 60 ■ Examining dependencies with cargo-tree 61 PART 2 CORE DATA..........................................................63 4 Data structures 65 4.1 Demystifying String, str, &str, and &'static str 66 String vs str 66 ■ Using strings effectively 67 4.2 Understanding slices and arrays 69 4.3 Vectors 72 Diving deeper into Vec 72 ■ Wrapping vectors 73 ■ Types related to vectors 74 4.4 Maps 74 Custom hashing functions 75 ■ Creating hashable types 76 4.5 Rust types: Primitives, structs, enums, and aliases 77 Using primitive types 77 ■ Using tuples 80 ■ Using structs 81 Using enums 84 ■ Using aliases 86 4.6 Error handling with Result 87 4.7 Converting types with From/Into 88 TryFrom and TryInto 90 ■ Best practices for type conversion using From and Into 90 4.8 Handling FFI compatibility with Rust’s types 90 5 Working with memory 93 5.1 Memory management: Heap and stack 94 5.2 Understanding ownership: Copies, borrowing, references, and moves 96 5.3 Deep copying 97 5.4 Avoiding copies 99 5.5 To box or not to box: Smart pointers 100 5.6 Reference counting 103 5.7 Clone on write 106
📄 Page 9
CONTENTS vii 5.8 Custom allocators 110 Writing a custom allocator 110 ■ Creating a custom allocator for protected memory 113 5.9 Smart pointers summarized 117 PART 3 CORRECTNESS ....................................................119 6 Unit testing 121 6.1 How testing is different in Rust 122 6.2 Review of built-in testing features 123 6.3 Testing frameworks 125 6.4 What not to test: Why the compiler knows better than you 128 6.5 Handling parallel test special cases and global state 129 6.6 Thinking about refactoring 134 6.7 Refactoring tools 134 Reformatting 135 ■ Renaming 135 ■ Relocating 136 Rewriting 137 6.8 Code coverage 138 6.9 Dealing with a changing ecosystem 140 7 Integration testing 141 7.1 Comparing integration and unit testing 142 7.2 Integration testing strategies 144 7.3 Built-in integration testing vs. external integration testing 146 7.4 Integration testing libraries and tooling 147 Using assert_cmd to test CLI applications 147 ■ Using proptest with integration tests 149 ■ Other integration testing tools 150 7.5 Fuzz testing 150 PART 4 ASYNCHRONOUS RUST.........................................155 8 Async Rust 157 8.1 Runtimes 159 8.2 Thinking asynchronously 159
📄 Page 10
CONTENTSviii 8.3 Futures: Handling async task results 161 Defining a runtime with #[tokio::main] 164 8.4 The async and .await keywords: When and where to use them 164 8.5 Concurrency and parallelism with async 166 8.6 Implementing an async observer 169 8.7 Mixing sync and async 174 8.8 When to avoid using async 176 8.9 Tracing and debugging async code 177 8.10 Dealing with async when testing 180 9 Building an HTTP REST API service 182 9.1 Choosing a web framework 183 9.2 Creating an architecture 184 9.3 API design 184 9.4 Libraries and tools 185 9.5 Application scaffolding 187 main() 187 ■ init_tracing() 188 ■ init_dbpool() 189 9.6 Data modeling 190 SQL schema 190 ■ Interfacing with our data 191 9.7 Declaring the API routes 194 9.8 Implementing the API routes 195 9.9 Error handling 197 9.10 Running the service 198 10 Building an HTTP REST API CLI 204 10.1 Deciding which tools and libraries to use 205 10.2 Designing the CLI 206 10.3 Declaring the commands 207 10.4 Implementing the commands 209 10.5 Implementing requests 210 10.6 Handling errors gracefully 211 10.7 Testing our CLI 212
📄 Page 11
CONTENTS ix PART 5 OPTIMIZATIONS ..................................................217 11 Optimizations 219 11.1 Zero-cost abstractions 220 11.2 Vectors 221 Vector memory allocation 221 ■ Vector iterators 223 ■ Fast copies with Vec and slices 225 11.3 SIMD 226 11.4 Parallelization with Rayon 227 11.5 Using Rust to accelerate other languages 229 11.6 Where to go from here 231 11.7 Installing tools for this book 233 Installing tools on macOS using Homebrew 233 ■ Installing tools on Linux systems 233 ■ Installing rustup on Linux- or UNIX- based systems 233 ■ Installing tools on Windows 234 11.8 Managing rustc and other Rust components with rustup 234 Installing rustc and other components 234 ■ Switching default toolchains with rustup 234 ■ Updating Rust components 234 Installing HTTPie 235 appendix 233 index 237
📄 Page 12
x preface I love learning new programming languages. I’ve been writing code for a long time, but I still find myself occasionally banging my head against a wall when learning new languages or tools. Rust is a unique lan- guage in many respects, and it introduces several concepts that some people may have never seen before, even if they have been programming for many years. I have spent a great deal of time working with Rust both professionally and as a contributor to community projects, and I have written this book to share what I learned along the way. By taking the time to read this book, you will save yourself a lot of time by avoiding the common pitfalls and problems people encounter when they’re new to Rust.
📄 Page 13
xi acknowledgments I’d like to thank my friends Javeed Shaikh and Ben Lin for providing feedback on early drafts of the manuscript as well as Manning Publications for working patiently with me in completing this book. Specifically, I would like to thank the development editor Karen Miller, the review editor Aleksandar Dragosavljević, the production editor Deirdre Hiam, the copyeditor Christian Berk, and the proofreader Katie Tennant. I thank all the reviewers—Adam Wendell, Alessandro Campeis, Arun Bhagvan Kommadi, Christian Witts, Clifford Thurber, David Moshal, David Paccoud, Gianluigi Spagnuolo, Horaci Macias, Jaume Lopez, Jean-Paul Malherbe, João Pedro de Lacerda, Jon Riddle, Joseph Pachod, Julien Castelain, Kevin Orr, Madhav Ayyagari, Martin Nowack, Matt Sarmiento, Matthew Winter, Matthias Busch, PK Chetty, Rohit Goswami, Satadru Roy, Satej Kumar Sahu, Sebastian Palma, Seth MacPherson, Simon Tschöke, Sri Kadimisetty, Tim van Deurzen, William Wheeler, and Zach Peters—your sugges- tions help to make this a better book.
📄 Page 14
xii about this book While writing this book, I’ve paid special attention to noting when features or inter- faces are subject to change. While core language features may not change substan- tially, practical use of Rust may involve hundreds of separate libraries and projects. By reading this book, you’ll be introduced to strategies and techniques that help you nav- igate this evolving ecosystem. As you continue to read, I would like to mention that the Rust ecosystem is rapidly evolving. I have written this book with the future of Rust in mind, but I cannot guaran- tee that the language and libraries won’t change substantially after the book has been published. How is this book different? This book focuses on the practical usage of Rust, while considering the big-picture themes, limitations of Rust and its tooling, and how developers can become produc- tive with Rust quickly. The text is not an introduction to the Rust language, nor is it a replacement for the official Rust documentation. This book supplements the existing documentation and resources available for Rust and provides the most important les- sons you won’t find in Rust documentation in one place. While Code Like a Pro in Rust does not provide an exhaustive reference for the Rust language, I do indicate where to go for additional information when appropriate.
📄 Page 15
ABOUT THIS BOOK xiii Who should read this book? Readers of this book should be familiar with Rust and consider themselves beginner to intermediate Rust programmers. If you have never used Rust, you may find this book difficult to read, as it contains many references to Rust-specific features, for which I will not spend much time discussing the background. If you find yourself con- fused about Rust syntax or technical details, I recommended starting with Rust in Action by Tim McNamara (Manning, 2021) or the official Rust book at https:// doc.rust-lang.org/book/. For those who are intermediate to advanced Rust programmers, some content in this book might be familiar. In your case, I recommend you skip ahead to the chapters most interesting to you. How this book is organized The chapters of this book can be read in any order, according to what interests you most. While I would like for every reader to read every chapter from start to finish, I also understand that readers have varied goals and experience levels. Most of the later chapters build on top of content from earlier chapters, so while it isn’t a requirement, you’ll get the most benefit from reading the chapters in order. Throughout the book, I make references to other chapters or topics as needed, and you may want to make notes to go back and read other sections accordingly. If you are relatively new to Rust or programming in general, then I recommend reading the whole book from cover to cover, to get the most out of it. For an excellent introduction to the Rust programming language, I recommend you first read the offi- cial Rust book (https://doc.rust-lang.org/book/). Part 1 covers an introduction to Rust and its tooling:  Chapter 1 provides an overview of Rust and what makes it special.  Chapter 2 introduces Cargo, Rust’s project management tool.  Chapter 3 provides a tour of key Rust tooling. Part 2 covers Rust’s data structures and memory management:  Chapter 4 discusses Rust data structures.  Chapter 5 goes into detail on Rust’s memory management model. Part 3 discusses testing methods for correctness:  Chapter 6 provides a tour of Rust’s unit testing features.  Chapter 7 dives into integration and fuzz testing. Part 4 introduces asynchronous Rust programming:  Chapter 8 provides an overview of Rust’s async features.  Chapter 9 walks through implementing an async HTTP server.  Chapter 10 walks through implementing an async HTTP client. Part 5 discusses optimizations:  Chapter 11 dives into the details of Rust optimizations.
📄 Page 16
ABOUT THIS BOOKxiv About the code This book contains many examples of source code both in numbered listings and in line with normal text. In both cases, source code is formatted in a fixed-width font like this to separate it from ordinary text. Sometimes code is also in bold to highlight code that has changed from previous steps in the chapter, such as when a new feature adds to an existing line of code. In many cases, the original source code has been reformatted; we’ve added line breaks and reworked indentation to accommodate the available page space in the book. In some cases, even this was not enough, and listings include line-continuation markers (➥). Additionally, comments in the source code have often been removed from the listings when the code is described in the text. Code annotations accompany many of the listings, highlighting important concepts. You can get executable snippets of code from the liveBook (online) version of this book at https://livebook.manning.com/book/code-like-a-pro-in-rust. The complete code for the examples in the book is available for download from the Manning web- site at https://www.manning.com/books/code-like-a-pro-in-rust, and from GitHub at https://github.com/brndnmtthws/code-like-a-pro-in-rust-book. You can clone a copy of the book’s code locally on your computer by running the following command with Git: $ git clone https://github.com/brndnmtthws/code-like-a-pro-in-rust-book The book’s code is organized into directories by chapter and section within the repos- itory, organized within each section by topic. The code is licensed under the MIT license, which is a permissive license that allows you to copy the code samples and use them as you see fit, even as the basis for your own work. Throughout this book, there are many references to open source projects which are used as teaching aids. The source code for most of these projects (or crates) can be obtained from their respective project repositories—for reference, see the follow- ing table. List of projects referenced in this book Name Description Home page Repository URL dryoc Cryptography library https://crates.io/crates/dryoc https://github.com/brndnmtthws/ dryoc.git rand Provides random values https://rust-random.github.io/book https://github.com/rust-random/ rand.git Rocket HTTP/web framework https://rocket.rs https://github.com/SergioBenitez/ Rocket.git num_cpus Returns the number of logical CPU cores https://crates.io/crates/num_cpus https://github.com/seanmonstar/ num_cpus.git zlib Compression library https://zlib.net/ https://github.com/madler/zlib.git
📄 Page 17
ABOUT THIS BOOK xv liveBook discussion forum Purchase of Code Like a Pro in Rust includes free access to liveBook, Manning’s online reading platform. Using liveBook’s exclusive discussion features, you can attach com- ments to the book globally or to specific sections or paragraphs. It’s a snap to make notes for yourself, ask and answer technical questions, and receive help from the author and other users. To access the forum, go to https://livebook.manning.com/ book/code-like-a-pro-in-rust. You can also learn more about Manning’s forums and the rules of conduct at https://livebook.manning.com/discussion. Manning’s commitment to our readers is to provide a venue where a meaningful dialogue between individual readers and between readers and the author can take place. It is not a commitment to any specific amount of participation on the part of the author, whose contribution to the forum remains voluntary (and unpaid). We sug- gest you try asking him some challenging questions lest his interest stray! The forum and the archives of previous discussions will be accessible from the publisher’s website as long as the book is in print. lazy_static Global static variable library https://crates.io/crates/lazy_static http://mng.bz/E9rD Tokio Async runtime https://tokio.rs https://github.com/tokio-rs/tokio Syn Rust code parser https://crates.io/crates/syn https://github.com/dtolnay/syn axum Async web framework https://docs.rs/axum/latest/axum/ https://github.com/tokio-rs/axum List of projects referenced in this book (continued) Name Description Home page Repository URL
📄 Page 18
xvi about the author BRENDEN MATTHEWS is a software engineer, entrepreneur, and prolific open source con- tributor. He has been using Rust since the early days of the language and has contrib- uted to several Rust tools and open source projects, in addition to using Rust professionally. He’s the author of Conky, a popular system monitor, and a member of the Apache Software Foundation, with over 25 years of industry experience. Brenden is also a YouTube contributor and instructor as well as an author of many articles on Rust and other programming languages. He has given talks at several technology con- ferences, including QCon, LinuxCon, ContainerCon, MesosCon, All Things Open, and Rust meetups. He has been a GitHub contributor for over 13 years, has multiple published Rust crates, has contributed to several open source Rust projects, and has built production-grade Rust applications professionally. Brenden is also the author of Rust Design Patterns, a follow-up to Code Like a Pro in Rust.
📄 Page 19
xvii about the cover illustration The figure on the cover of Code Like a Pro in Rust is “Femme de l’Argou,” or “Woman of Aargau, Switzerland,” taken from a collection by Jacques Grasset de Saint-Sauveur, published in 1797. Each illustration is finely drawn and colored by hand. In those days, it was easy to identify where people lived and what their trade or sta- tion in life was just by their dress. Manning celebrates the inventiveness and initiative of the computer business with book covers based on the rich diversity of regional cul- ture centuries ago, brought back to life by pictures from collections such as this one.
📄 Page 20
(This page has no text content)
The above is a preview of the first 20 pages. Register to read the complete e-book.

💝 Support Author

0.00
Total Amount (¥)
0
Donation Count

Login to support the author

Login Now
Back to List