Programming
Rust
FAST, SAFE SYSTEMS DEVELOPMENT
Jim Blandy & Jason Orendorff
Programming Rust
Fast, Safe Systems Development
Jim Blandy and Jason Orendorff
Beijing
Beijing
Boston
Boston
Farnham Sebastopol
Farnham Sebastopol
Tokyo
Tokyo
Programming Rust
by Jim Blandy and Jason Orendorff
Copyright © 2018 Jim Blandy, Jason Orendorff. All rights reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.
O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are
also available for most titles (http://safaribooksonline.com). For more information, contact our corporate/
institutional sales department: 800-998-9938 or corporate@oreilly.com.
Editors: Jeff Bleiel
Production Editor: Colleen Cole
Copyeditor: Jasmine Kwityn
Proofreader: Sharon Wilkey
Indexer: WordCo Indexing Services, Inc.
Interior Designer: David Futato
Cover Designer: Karen Montgomery
Illustrator: Rebecca Demarest
December 2017:
First Edition
Revision History for the First Edition
2017-11-20: First Release
See http://oreilly.com/catalog/errata.csp?isbn=9781491927212 for release details.
The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Programming Rust, the cover image,
and related trade dress are trademarks of O’Reilly Media, Inc.
While the publisher and the authors have used good faith efforts to ensure that the information and
instructions contained in this work are accurate, the publisher and the authors disclaim all responsibility
for errors or omissions, including without limitation responsibility for damages resulting from the use of
or reliance on this work. Use of the information and instructions contained in this work is at your own
risk. If any code samples or other technology this work contains or describes is subject to open source
licenses or the intellectual property rights of others, it is your responsibility to ensure that your use
thereof complies with such licenses and/or rights.
978-1-491-92728-1
[M]
Table of Contents
Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xv
1. Why Rust?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Type Safety 3
2. A Tour of Rust. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Downloading and Installing Rust 7
A Simple Function 10
Writing and Running Unit Tests 11
Handling Command-Line Arguments 12
A Simple Web Server 17
Concurrency 23
What the Mandelbrot Set Actually Is 24
Parsing Pair Command-Line Arguments 28
Mapping from Pixels to Complex Numbers 31
Plotting the Set 32
Writing Image Files 33
A Concurrent Mandelbrot Program 35
Running the Mandelbrot Plotter 40
Safety Is Invisible 41
3. Basic Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
Machine Types 46
Integer Types 47
Floating-Point Types 50
The bool Type 51
Characters 52
Tuples 54
iii
Pointer Types 55
References 56
Boxes 56
Raw Pointers 57
Arrays, Vectors, and Slices 57
Arrays 58
Vectors 59
Building Vectors Element by Element 62
Slices 62
String Types 64
String Literals 64
Byte Strings 65
Strings in Memory 65
String 67
Using Strings 68
Other String-Like Types 68
Beyond the Basics 69
4. Ownership. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
71
Ownership 73
Moves 77
More Operations That Move 82
Moves and Control Flow 84
Moves and Indexed Content 84
Copy Types: The Exception to Moves 86
Rc and Arc: Shared Ownership 90
5. References. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
References as Values 97
Rust References Versus C++ References 97
Assigning References 98
References to References 99
Comparing References 99
References Are Never Null 100
Borrowing References to Arbitrary Expressions 100
References to Slices and Trait Objects 101
Reference Safety 101
Borrowing a Local Variable 101
Receiving References as Parameters 105
Passing References as Arguments 107
Returning References 107
Structs Containing References 109
iv
|
Table of Contents
Distinct Lifetime Parameters 111
Omitting Lifetime Parameters 112
Sharing Versus Mutation 114
Taking Arms Against a Sea of Objects 121
6. Expressions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
An Expression Language 123
Blocks and Semicolons 124
Declarations 126
if and match 127
if let 129
Loops 130
return Expressions 132
Why Rust Has loop 133
Function and Method Calls 134
Fields and Elements 135
Reference Operators 137
Arithmetic, Bitwise, Comparison, and Logical Operators 137
Assignment 138
Type Casts 139
Closures 140
Precedence and Associativity 140
Onward 142
7. Error Handling. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
Panic 145
Unwinding 146
Aborting 147
Result 148
Catching Errors 148
Result Type Aliases 150
Printing Errors 150
Propagating Errors 152
Working with Multiple Error Types 153
Dealing with Errors That “Can’t Happen” 155
Ignoring Errors 156
Handling Errors in main() 156
Declaring a Custom Error Type 157
Why Results? 158
8. Crates and Modules. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
Crates 161
Table of Contents
|
v
Build Profiles 164
Modules 165
Modules in Separate Files 166
Paths and Imports 167
The Standard Prelude 169
Items, the Building Blocks of Rust 170
Turning a Program into a Library 172
The src/bin Directory 174
Attributes 175
Tests and Documentation 178
Integration Tests 180
Documentation 181
Doc-Tests 182
Specifying Dependencies 185
Versions 186
Cargo.lock 187
Publishing Crates to crates.io 188
Workspaces 190
More Nice Things 191
9. Structs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
Named-Field Structs 193
Tuple-Like Structs 196
Unit-Like Structs 197
Struct Layout 197
Defining Methods with impl 198
Generic Structs 202
Structs with Lifetime Parameters 203
Deriving Common Traits for Struct Types 204
Interior Mutability 205
10. Enums and Patterns. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
Enums 212
Enums with Data 214
Enums in Memory 215
Rich Data Structures Using Enums 216
Generic Enums 218
Patterns 221
Literals, Variables, and Wildcards in Patterns 223
Tuple and Struct Patterns 225
Reference Patterns 226
Matching Multiple Possibilities 229
vi
|
Table of Contents