102847
102847
com
https://textbookfull.com/product/the-rust-programming-
language-2nd-edition-steve-klabnik/
OR CLICK HERE
DOWLOAD EBOOK
https://textbookfull.com/product/the-rust-programming-language-covers-
rust-2018-steve-klabnik/
textbookfull.com
https://textbookfull.com/product/the-rust-programming-language-1st-
edition-steve-klabnik/
textbookfull.com
https://textbookfull.com/product/the-rust-programming-language-2nd-
edition-steve-klabnik-and-carol-nichols/
textbookfull.com
https://textbookfull.com/product/programming-rust-2nd-edition-early-
release-jim-blandy/
textbookfull.com
Programming Rust 1st Edition Jim Blandy
https://textbookfull.com/product/programming-rust-1st-edition-jim-
blandy/
textbookfull.com
https://textbookfull.com/product/the-complete-rust-programming-
reference-guide-rahul-sharma/
textbookfull.com
https://textbookfull.com/product/programming-webassembly-with-
rust-1st-edition-kevin-hoffman/
textbookfull.com
https://textbookfull.com/product/network-programming-with-rust-1st-
edition-abhishek-chanda/
textbookfull.com
https://textbookfull.com/product/asynchronous-programming-in-rust-1st-
edition-carl-fredrik-samson/
textbookfull.com
THE RUST PROGRAMMING LANGUAGE
THE RUST
PROGRAMMING
LANGUAGE
2nd Edition
by S t e v e K l a b n i k a n d C a r o l N i c h o ls ,
w it h con t r i b u t i o n s f r o m
t h e Ru s t C o m m u n i t y
San Francisco
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.
Third printing
27 26 25 24 23 34567
For customer service inquiries, please contact [email protected]. For information on distribution,
bulk sales, corporate sales, or translations: [email protected]. For permission to translate this work:
[email protected]. To report counterfeit copies or piracy: [email protected].
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.
About the Authors
Steve Klabnik was the lead for the Rust documentation team and was one
of Rust’s core developers. A frequent speaker and a prolific open source con-
tributor, he previously worked on projects such as Ruby and Ruby on Rails.
Carol Nichols is a member of the Rust Crates.io Team and a former mem-
ber of the Rust Core Team. She’s a co-founder of Integer 32, LLC, the
world’s first Rust-focused software consultancy. Nichols has also organized
the Rust Belt Rust Conference.
Foreword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xix
Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxi
Acknowledgments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxiii
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxv
Chapter 7: Managing Growing Projects with Packages, Crates, and Modules . . . . . . . . . . 119
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 517
FOREWORD xix
PREFACE xxi
ACKNOWLEDGMENTS xxiii
INTRODUCTION xxv
Who Rust Is For . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxvi
Teams of Developers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxvi
Students . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxvi
Companies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxvi
Open Source Developers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxvii
People Who Value Speed and Stability . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxvii
Who This Book Is For . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxvii
How to Use This Book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxvii
Resources and How to Contribute to This Book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxix
1
GETTING STARTED 1
Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Installing rustup on Linux or macOS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Installing rustup on Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Updating and Uninstalling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Local Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Hello, World! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Creating a Project Directory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Writing and Running a Rust Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Anatomy of a Rust Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Compiling and Running Are Separate Steps . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Hello, Cargo! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Creating a Project with Cargo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Building and Running a Cargo Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Building for Release . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Cargo as Convention . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
2
PROGRAMMING A GUESSING GAME 13
Setting Up a New Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Processing a Guess . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Storing Values with Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Receiving User Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Handling Potential Failure with Result . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Printing Values with println! Placeholders . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
Testing the First Part . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Generating a Secret Number . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Using a Crate to Get More Functionality . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Generating a Random Number . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
Comparing the Guess to the Secret Number . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
Allowing Multiple Guesses with Looping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
Quitting After a Correct Guess . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
Handling Invalid Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
3
COMMON PROGRAMMING CONCEPTS 31
Variables and Mutability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
Shadowing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
Scalar Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
Compound Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
Statements and Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
Functions with Return Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
Control Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
if Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
Repetition with Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
4
UNDERSTANDING OWNERSHIP 59
What Is Ownership? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
Ownership Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
Variable Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
The String Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
Memory and Allocation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
Ownership and Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
Return Values and Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
References and Borrowing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
Mutable References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
Dangling References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
The Rules of References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
The Slice Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
String Slices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
Other Slices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
x Contents in Detail
5
USING STRUCTS TO STRUCTURE RELATED DATA 85
Defining and Instantiating Structs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
Using the Field Init Shorthand . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
Creating Instances from Other Instances with Struct Update Syntax . . . . . . . . . 88
Using Tuple Structs Without Named Fields to Create Different Types . . . . . . . . . 89
Unit-Like Structs Without Any Fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
An Example Program Using Structs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
Refactoring with Tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
Refactoring with Structs: Adding More Meaning . . . . . . . . . . . . . . . . . . . . . . 93
Adding Useful Functionality with Derived Traits . . . . . . . . . . . . . . . . . . . . . . . 94
Method Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
Defining Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
Methods with More Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
Associated Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
Multiple impl Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
6
ENUMS AND PATTERN MATCHING 103
Defining an Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
Enum Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
The Option Enum and Its Advantages Over Null Values . . . . . . . . . . . . . . . . 108
The match Control Flow Construct . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
Patterns That Bind to Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
Matching with Option<T> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
Matches Are Exhaustive . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
Catch-All Patterns and the _ Placeholder . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
Concise Control Flow with if let . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
7
MANAGING GROWING PROJECTS
WITH PACKAGES, CRATES, AND MODULES 119
Packages and Crates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
Defining Modules to Control Scope and Privacy . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
Paths for Referring to an Item in the Module Tree . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
Exposing Paths with the pub Keyword . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
Starting Relative Paths with super . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
Making Structs and Enums Public . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
Bringing Paths into Scope with the use Keyword . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
Creating Idiomatic use Paths . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
Providing New Names with the as Keyword . . . . . . . . . . . . . . . . . . . . . . . . 135
Re-exporting Names with pub use . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
Using External Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136
Using Nested Paths to Clean Up Large use Lists . . . . . . . . . . . . . . . . . . . . . . 137
The Glob Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
Separating Modules into Different Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
Contents in Detail xi
8
COMMON COLLECTIONS 141
Storing Lists of Values with Vectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142
Creating a New Vector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142
Updating a Vector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142
Reading Elements of Vectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
Iterating Over the Values in a Vector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
Using an Enum to Store Multiple Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
Dropping a Vector Drops Its Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
Storing UTF-8 Encoded Text with Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
What Is a String? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
Creating a New String . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
Updating a String . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
Indexing into Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
Slicing Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
Methods for Iterating Over Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
Strings Are Not So Simple . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154
Storing Keys with Associated Values in Hash Maps . . . . . . . . . . . . . . . . . . . . . . . . . . 154
Creating a New Hash Map . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154
Accessing Values in a Hash Map . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
Hash Maps and Ownership . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
Updating a Hash Map . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
Hashing Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
9
ERROR HANDLING 161
Unrecoverable Errors with panic! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
Recoverable Errors with Result . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
Matching on Different Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
Propagating Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
To panic! or Not to panic! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
Examples, Prototype Code, and Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
Cases in Which You Have More Information Than the Compiler . . . . . . . . . . 176
Guidelines for Error Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176
Creating Custom Types for Validation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
10
GENERIC TYPES, TRAITS, AND LIFETIMES 181
Removing Duplication by Extracting a Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
Generic Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
In Function Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
In Struct Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
In Enum Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
In Method Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
Performance of Code Using Generics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191
Traits: Defining Shared Behavior . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192
Defining a Trait . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192
Implementing a Trait on a Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
Default Implementations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195
11
WRITING AUTOMATED TESTS 215
How to Write Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216
The Anatomy of a Test Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216
Checking Results with the assert! Macro . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
Testing Equality with the assert_eq! and assert_ne! Macros . . . . . . . . . . . . . . 222
Adding Custom Failure Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
Checking for Panics with should_panic . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
Using Result<T, E> in Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
Controlling How Tests Are Run . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
Running Tests in Parallel or Consecutively . . . . . . . . . . . . . . . . . . . . . . . . . . 231
Showing Function Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
Running a Subset of Tests by Name . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
Ignoring Some Tests Unless Specifically Requested . . . . . . . . . . . . . . . . . . . . 235
Test Organization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236
Unit Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236
Integration Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242
12
AN I/O PROJECT: BUILDING A COMMAND LINE PROGRAM 243
Accepting Command Line Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244
Reading the Argument Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244
Saving the Argument Values in Variables . . . . . . . . . . . . . . . . . . . . . . . . . . 246
Reading a File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247
Refactoring to Improve Modularity and Error Handling . . . . . . . . . . . . . . . . . . . . . . . 248
Separation of Concerns for Binary Projects . . . . . . . . . . . . . . . . . . . . . . . . . 249
Fixing the Error Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
Extracting Logic from main . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256
Splitting Code into a Library Crate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258
Developing the Library’s Functionality with Test-Driven Development . . . . . . . . . . . . . . 259
Writing a Failing Test . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 260
Writing Code to Pass the Test . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262
13
FUNCTIONAL LANGUAGE FEATURES:
ITERATORS AND CLOSURES 273
Closures: Anonymous Functions That Capture Their Environment . . . . . . . . . . . . . . . . . 274
Capturing the Environment with Closures . . . . . . . . . . . . . . . . . . . . . . . . . . 274
Closure Type Inference and Annotation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276
Capturing References or Moving Ownership . . . . . . . . . . . . . . . . . . . . . . . . 278
Moving Captured Values Out of Closures and the Fn Traits . . . . . . . . . . . . . . 280
Processing a Series of Items with Iterators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284
The Iterator Trait and the next Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285
Methods That Consume the Iterator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286
Methods That Produce Other Iterators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286
Using Closures That Capture Their Environment . . . . . . . . . . . . . . . . . . . . . . 287
Improving Our I/O Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289
Removing a clone Using an Iterator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289
Making Code Clearer with Iterator Adapters . . . . . . . . . . . . . . . . . . . . . . . . 292
Choosing Between Loops and Iterators . . . . . . . . . . . . . . . . . . . . . . . . . . . . 292
Comparing Performance: Loops vs. Iterators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294
14
MORE ABOUT CARGO AND CRATES.IO 295
Customizing Builds with Release Profiles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296
Publishing a Crate to Crates.io . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297
Making Useful Documentation Comments . . . . . . . . . . . . . . . . . . . . . . . . . . 297
Exporting a Convenient Public API with pub use . . . . . . . . . . . . . . . . . . . . . . 300
Setting Up a Crates.io Account . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304
Adding Metadata to a New Crate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304
Publishing to Crates.io . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
Publishing a New Version of an Existing Crate . . . . . . . . . . . . . . . . . . . . . . . 306
Deprecating Versions from Crates.io with cargo yank . . . . . . . . . . . . . . . . . . 306
Cargo Workspaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307
Creating a Workspace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307
Creating the Second Package in the Workspace . . . . . . . . . . . . . . . . . . . . . 308
Installing Binaries with cargo install . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312
Extending Cargo with Custom Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313
15
SMART POINTERS 315
Using Box<T> to Point to Data on the Heap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316
Using Box<T> to Store Data on the Heap . . . . . . . . . . . . . . . . . . . . . . . . . . 317
Enabling Recursive Types with Boxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317
16
FEARLESS CONCURRENCY 353
Using Threads to Run Code Simultaneously . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354
Creating a New Thread with spawn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355
Waiting for All Threads to Finish Using join Handles . . . . . . . . . . . . . . . . . . 356
Using move Closures with Threads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358
Using Message Passing to Transfer Data Between Threads . . . . . . . . . . . . . . . . . . . . . 361
Channels and Ownership Transference . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363
Sending Multiple Values and Seeing the Receiver Waiting . . . . . . . . . . . . . . 364
Creating Multiple Producers by Cloning the Transmitter . . . . . . . . . . . . . . . . . 365
Shared-State Concurrency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367
Using Mutexes to Allow Access to Data from One Thread at a Time . . . . . . . . 367
Similarities Between RefCell<T>/Rc<T> and Mutex<T>/Arc<T> . . . . . . . . . . . 372
Extensible Concurrency with the Send and Sync Traits . . . . . . . . . . . . . . . . . . . . . . . . 373
Allowing Transference of Ownership Between Threads with Send . . . . . . . . . 373
Allowing Access from Multiple Threads with Sync . . . . . . . . . . . . . . . . . . . . 373
Implementing Send and Sync Manually Is Unsafe . . . . . . . . . . . . . . . . . . . . . 374
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374
17
OBJECT-ORIENTED PROGRAMMING FEATURES 375
Characteristics of Object-Oriented Languages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376
Objects Contain Data and Behavior . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376
Encapsulation That Hides Implementation Details . . . . . . . . . . . . . . . . . . . . . 376
Inheritance as a Type System and as Code Sharing . . . . . . . . . . . . . . . . . . . 378
Using Trait Objects That Allow for Values of Different Types . . . . . . . . . . . . . . . . . . . . 379
Defining a Trait for Common Behavior . . . . . . . . . . . . . . . . . . . . . . . . . . . . 380
Implementing the Trait . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 381
Trait Objects Perform Dynamic Dispatch . . . . . . . . . . . . . . . . . . . . . . . . . . . 384
Implementing an Object-Oriented Design Pattern . . . . . . . . . . . . . . . . . . . . . . . . . . . 384
Defining Post and Creating a New Instance in the Draft State . . . . . . . . . . . . 386
Storing the Text of the Post Content . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 387
Contents in Detail xv
Ensuring the Content of a Draft Post Is Empty . . . . . . . . . . . . . . . . . . . . . . . . 387
Requesting a Review Changes the Post’s State . . . . . . . . . . . . . . . . . . . . . . . 388
Adding approve to Change the Behavior of content . . . . . . . . . . . . . . . . . . . 389
Trade-offs of the State Pattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 396
18
PATTERNS AND MATCHING 397
All the Places Patterns Can Be Used . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 398
match Arms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 398
Conditional if let Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 399
while let Conditional Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 400
for Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 400
let Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 401
Function Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 402
Refutability: Whether a Pattern Might Fail to Match . . . . . . . . . . . . . . . . . . . . . . . . . . 403
Pattern Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 405
Matching Literals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 405
Matching Named Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 405
Multiple Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 406
Matching Ranges of Values with ..= . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 406
Destructuring to Break Apart Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407
Ignoring Values in a Pattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411
Extra Conditionals with Match Guards . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415
@ Bindings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 417
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 418
19
ADVANCED FEATURES 419
Unsafe Rust . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 420
Unsafe Superpowers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 420
Dereferencing a Raw Pointer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421
Calling an Unsafe Function or Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . 423
Accessing or Modifying a Mutable Static Variable . . . . . . . . . . . . . . . . . . . . 427
Implementing an Unsafe Trait . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 429
Accessing Fields of a Union . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 429
When to Use Unsafe Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 429
Advanced Traits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 430
Associated Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 430
Default Generic Type Parameters and Operator Overloading . . . . . . . . . . . . 431
Disambiguating Between Methods with the Same Name . . . . . . . . . . . . . . . . 433
Using Supertraits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 437
Using the Newtype Pattern to Implement External Traits . . . . . . . . . . . . . . . . . 439
Advanced Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 440
Using the Newtype Pattern for Type Safety and Abstraction . . . . . . . . . . . . . . 440
Creating Type Synonyms with Type Aliases . . . . . . . . . . . . . . . . . . . . . . . . . 440
The Never Type That Never Returns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443
Dynamically Sized Types and the Sized Trait . . . . . . . . . . . . . . . . . . . . . . . . 444
Advanced Functions and Closures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 446
Function Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 446
Returning Closures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 448
20
FINAL PROJECT: BUILDING A MULTITHREADED WEB SERVER 459
Building a Single-Threaded Web Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 460
Listening to the TCP Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 461
Reading the Request . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 462
A Closer Look at an HTTP Request . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 464
Writing a Response . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 465
Returning Real HTML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 466
Validating the Request and Selectively Responding . . . . . . . . . . . . . . . . . . . . 467
A Touch of Refactoring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 469
Turning Our Single-Threaded Server into a Multithreaded Server . . . . . . . . . . . . . . . . 471
Simulating a Slow Request . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 471
Improving Throughput with a Thread Pool . . . . . . . . . . . . . . . . . . . . . . . . . . 472
Graceful Shutdown and Cleanup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487
Implementing the Drop Trait on ThreadPool . . . . . . . . . . . . . . . . . . . . . . . . . 487
Signaling to the Threads to Stop Listening for Jobs . . . . . . . . . . . . . . . . . . . . 490
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493
A
KEYWORDS 495
Keywords Currently in Use . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 495
Keywords Reserved for Future Use . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 497
Raw Identifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 497
B
OPERATORS AND SYMBOLS 499
Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 499
Non-operator Symbols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 502
C
DERIVABLE TRAITS 507
Debug for Programmer Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 508
PartialEq and Eq for Equality Comparisons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 508
PartialOrd and Ord for Ordering Comparisons . . . . . . . . . . . . . . . . . . . . . . . . . . . . 509
Clone and Copy for Duplicating Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 509
Hash for Mapping a Value to a Value of Fixed Size . . . . . . . . . . . . . . . . . . . . . . . . . 510
Default for Default Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 510
E
EDITIONS 515
INDEX 517
xx Foreword
PR E FAC E
This version of the text assumes you’re using Rust 1.62.0 (released 2022-06-30)
or later with edition="2021" in the Cargo.toml file of all projects to config-
ure them to use Rust 2021 edition idioms. See “Installation” on page 1 for
instructions on installing or updating Rust, and see Appendix E for infor-
mation on editions.
The 2021 edition of the Rust language includes a number of improve-
ments that make Rust more ergonomic and that correct some inconsistencies.
On top of a general update to reflect these improvements, this rendition of
the book has a number of improvements to address specific feedback:
Note that any code from earlier renditions of this book that compiled
will continue to compile with the relevant edition in the project’s Cargo.toml,
even as you update the Rust compiler version you’re using. That’s Rust’s
backward-compatibility guarantees at work!
ACKNOW LEDGMENT S
We would like to thank everyone who has worked on the Rust language for
creating an amazing language worth writing a book about. We’re grateful
to everyone in the Rust community for being welcoming and creating an
environment worth welcoming more folks into.
We’re especially thankful for everyone who read early versions of this
book online and provided feedback, bug reports, and pull requests. Special
thanks to Eduard-Mihai Burtescu, Alex Crichton, and JT for providing
technical review, and to Karen Rustad Tölva for the cover art. Thank you
to our team at No Starch, including Bill Pollock, Liz Chadwick, and Janelle
Ludowise, for improving this book and bringing it to print.
Carol is grateful for the opportunity to work on this book. She thanks
her family for their constant love and support, especially her husband,
Jake Goulding, and her daughter, Vivian.
INTRODUCTION
Teams of Developers
Rust is proving to be a productive tool for collaborating among large teams
of developers with varying levels of systems programming knowledge. Low-
level code is prone to various subtle bugs, which in most other languages
can only be caught through extensive testing and careful code review by
experienced developers. In Rust, the compiler plays a gatekeeper role by
refusing to compile code with these elusive bugs, including concurrency
bugs. By working alongside the compiler, the team can spend their time
focusing on the program’s logic rather than chasing down bugs.
Rust also brings contemporary developer tools to the systems program-
ming world:
• Cargo, the included dependency manager and build tool, makes add-
ing, compiling, and managing dependencies painless and consistent
across the Rust ecosystem.
• The rustfmt formatting tool ensures a consistent coding style across
developers.
• The Rust Language Server powers integrated development environment
(IDE) integration for code completion and inline error messages.
By using these and other tools in the Rust ecosystem, developers can be
productive while writing systems-level code.
Students
Rust is for students and those who are interested in learning about systems
concepts. Using Rust, many people have learned about topics like operat-
ing systems development. The community is very welcoming and happy
to answer students’ questions. Through efforts such as this book, the Rust
teams want to make systems concepts more accessible to more people, espe-
cially those new to programming.
Companies
Hundreds of companies, large and small, use Rust in production for a vari-
ety of tasks, including command line tools, web services, DevOps tooling,
embedded devices, audio and video analysis and transcoding, cryptocur-
rencies, bioinformatics, search engines, Internet of Things applications,
machine learning, and even major parts of the Firefox web browser.
xxvi Introduction
Open Source Developers
Rust is for people who want to build the Rust programming language, com-
munity, developer tools, and libraries. We’d love to have you contribute to
the Rust language.
Introduction xxvii
Random documents with unrelated
content Scribd suggests to you:
came alongside and handed on board some newspapers, asking
if we would give a free passage to eleven riggers, as we were
going to Liverpool, and the tug was not going until she got a
tow. The riggers were taken on board. At a quarter to eight on
Tuesday evening were abreast of the Skerries, distant about a
mile and a half. At this time the wind had increased to a heavy
gale, and the ship was making little or no progress in the water.
She was driving up with the strength of the tide, and nearing
the shore; the steam had no effect, but we did all to keep the
ship off. The maintopsail was lowered, but she still drifted.
Clewed up the maintopsail, and the hands were sent up to furl
it. The wind had now increased considerably, almost blew the
sail from the yard, and it became entangled on the starboard
side. It was difficult to get the sail stowed. At this time Mr.
Bean, the third officer, with several seamen and myself, were
trying to make the sail fast, but could not succeed in
accomplishing it. Shortly afterwards orders were given to cock-
bill the port anchor, and let go. This was done, giving her
seventy-five fathoms of chain. The vessel was steaming the
whole time. Finding she was dragging, we let go the starboard
anchor. Still finding her dragging, we paid out all the port chain.
The vessel was still steaming, and the wind had now increased
to a perfect hurricane. We then went to get the stream anchor
up, and while doing so the starboard chain parted. I then felt
the ship canting over to port, and fancied the wind had
changed.
‘Orders were then given to cut away the mainmast, which was
done, and in a few minutes afterwards she struck on a bank.
The captain gave orders to the engineer to give her as much
steam as he could, to harden her on the bank. It was then
about three-quarters ebb tide. The place where she struck was
at the west of Moelfra, eastward of Point Lynas. Heard the
captain give orders to starboard the helm, to keep her on the
shore, so that the sea would not have so much power on her
broadside. When she became hardened on, the chief officer
gave me and the boatswain orders to cut the main and
maintopmast stays, as they were lying across the boat, so that
the boat could be cleared in case of need. We did so. The chief
boatswain and myself were afterwards sitting on a spar, on the
deck-house, the sea at the time making a complete breach over
the ship. I then went forward to look out, and ascertain whether
we were on sand or rock, when I discovered the land distant
about thirty yards. I went back, and told the chief officer that it
was land; and he said, “We will loose the foretopmast-staysail,
and when the tide makes up run her up.” I said it would be as
well to give her the foresail. It was then getting daylight. I
volunteered to go ashore with a line to get a hawser ashore,
immediately after which I felt the ship striking heavier than ever,
supposing it was in consequence of the tide making. The sea
still broke over her with even greater violence than ever. The
captain was at this time on deck, standing by the steam
telegraph. I told the chief officer again I was willing to go
ashore with a line, and do everything to save life. Asked him if
he would allow me a few minutes to put my lifebelt on; and he
said of course he would. I afterwards told the boatswain I was
going to try and get a line on shore, and he said it was useless,
the sea was running too high. Afterwards had a small line slung
round my body, and wished some one to volunteer to attend to
it while I swam ashore. After some hesitation, a man
volunteered. Just as I was being lowered into the water, some
one called out that there was a line on shore from forward.
Upon hearing that I did not go. A hawser was got on shore and
made fast to a rock, and with this contrivance myself and some
of the other seamen saved our lives. The hawser was made fast
by several of the inhabitants on shore, who came to render
assistance.
‘After the ship struck, all the passengers were directed to go aft
until the hawser could be properly got out, so that as many as
possible might be saved. Shortly after this the vessel parted
amidships; and a large number of passengers, standing on the
deck where she parted, were swept into the sea and drowned.
The boats were smashed to pieces by the fury of the gale, and
the others could not be lowered, so that none of them could be
made available. The passengers saved were driven on shore by
the force of the waves. Sixteen of the crew got ashore by the
hawser. An endeavour was made to get a second hawser ashore
to rescue the female passengers; but this could not be
accomplished. Not a single female passenger was saved. In
three hours after the vessel struck she began to go to pieces.
Saw about seventy passengers on the port bow, all anxiously
awaiting some means of getting them on shore; but a heavy sea
which struck the starboard bow stove it in, the ship gave a
lurch, and the people were all driven into the sea and drowned.
Some of the passengers saved were thrown upon the rocks, and
picked up by the crew and others who came to render
assistance.’
From the narratives, then, of Mr. Russell and the Boatswain’s Mate,
this much may be gathered—that the ‘Royal Charter’ had drifted
(shall we say had been foolishly allowed to drift?) too near the
coast; that the hurricane had gradually increased, and as the vessel
laboured so heavily, the masts had been cut away to ease her; that
the screw, which had to an extent served to keep the ship from
striking, became suddenly entangled with the falling spars, and
ceased to work; that the strong wind and stronger waves then bore
the craft against the rocks; that, through the courage of a seaman, a
rope was carried to the coast with a ‘boatswain’s chair’ secured upon
it; that (when a sufficient number of the crew had landed to work
‘this contrivance’) the passengers had been summoned to be sent
ashore; that, just as they were congregating amidships, a crash was
heard, the vessel parted, and fell to pieces like a house of cards;
that a few hasty farewells, a quick exchange of hopeless glances, a
waving of hands which heretofore had been joined in all life’s
struggles, and a last wild cry to heaven, through which the wintry
sun was slowly breaking, followed that awful crash; that the ship
gradually sank and the sea gradually swelled; that a few bodies,
cruelly mutilated, were washed upon the shelving crags; that the
sun rose higher and higher, until at length its beams flickered among
the crimson gouts upon the faces of the rocks; and, finally, that the
Welsh villagers gathered upon the spot, and, with true Welsh
hospitality, bore the bodies of the unfortunate passengers to their
homes.
And the sun set and the moon came up; and the wives of the
officers and crew—and all those who knew, or thought, they had
friends or relatives on board—assembled upon the spot, searching
along the shore for tokens or memorials however slight from which
LIFE or DEATH might be interpreted, and suspense changed, for better
or for worse, to certainty.
Other narratives come in at this point, all more or less afflicting. The
first is that of James Dean, which is remarkable as showing how, in the
most harrowing exigencies, the presence of mind of some men
never deserts them. Dean is a smith returned from Melbourne, and
he speaks bravely and bluffly, after the manner of his class. In
reading his story, it is well to mark the religion and heroism which
breathe through the words I have underlined.
Mr. John Bradbury speaks not only on the accident, but gives us a
glimpse of the earlier portion of the voyage. His sufferings on
escaping from the wreck were very great, and will serve as a hint of
what may have been endured before death by many of those whose
bones are now bleaching beneath the waters. But for his athletic
person and robust constitution, John Bradbury—who speaks as
under—would, without doubt, have been numbered with the lost:—
That the captain was in some degree ignorant of the exact spot
where he was, and was but imperfectly acquainted with the coast,
seems manifest from this,—when the hurricane gathered in its
might, it was proposed that a barrel of tar should be fired and sent
adrift, in order to light up the coast. ‘When the vessel struck,’ says
one of the daily newspaper reports, ‘signal guns were fired, rockets
sent off, and every means adopted to attract attention from the
shore; but the houses in the neighbourhood being few and far
between, no practicable assistance was attracted. No life-boat could
live in the raging sea, and the boats of the vessel herself were
perfectly unavailable.’
From the foregoing, a picture only too vivid of the catastrophe may
be realized. The Boatswain’s Mate describes the storm; Mr. Russell
paints the ship with all its intense and death-foreboding excitement;
and Mr. Bradbury conveys, with dread distinctness, the manner in
which the handful of saved fought their way from the jaws of death.
One or two other narratives, purporting to be from survivors, have
appeared, but as they are mere paraphrases of those I have given, I
have some doubt in the first place of their genuineness, and in the
second of the desirability of occupying space with repetitions.
Let the description of the night of the wreck end here.
The moment the news of the disaster reached London and Liverpool,
agents from Lloyd’s and the owners of the ship were despatched to
Molfre Bay. They were accompanied by representatives of the
principal London and Liverpool journals, and the communications
which the reporters subsequently addressed to their several papers
were affecting in the extreme. Here is the first:—
That one brief paragraph will attest to the colony how deep is the
sympathy entertained in England for the friends of those who are
lost. Had it been practicable to put off the feast to a more
convenient season it would have been done. The committee met and
considered the matter, and found it was impossible. The shadow of
the lost ship, however, rested upon the banquet!
How could it be otherwise? The day before, the inquest on the
bodies of some of the lost voyagers had been opened, and the
following heartrending description of it appeared in the Saturday’s
papers which the banqueters must have bought on their way, from
all parts of the country, to Liverpool:—
‘Four more bodies, all males, have been cast ashore since my
communication of yesterday—one last night and three this
morning. Three of them are now lying in the parish church of
Llanallgo; the remaining body has been removed to the church
of Penrhos Lligny, having been thrown ashore in the latter
parish. All yesterday evening a very heavy sea rolled; and about
four o’clock the lifeboat, manned by a crew of eight, put out to
rescue those on board a brigantine, which was observed to be
rapidly approaching the rocks a little to the north of the spot in
Dulas Bay, in which the wreck of the “Royal Charter” lies. The
brigantine, however, got safely in on the sands, in a little creek
about a mile from Molfra, where she now lies. As the waves
beat violently in on the Dulas Rocks last evening, large
quantities of clothing were to be seen tossed about. Some of it
was cast ashore, but a great deal was carried out to sea again.
It has been suggested by some of the relatives of the drowned
passengers and seamen, that if boats were sent out many more
bodies would be recovered. I think this extremely likely, after
what I have witnessed with respect to the action of the waves
on the clothing and spars. The Rev. Mr. Hughes is about to take
the matter in hand. There has been some objection on the part
of the authorities, as they apprehend that thefts might be
committed by some of the persons going out in the boats; but if
rumour speaks truly the watchers themselves require watching.
It is unfair to make charges against men having a responsible
duty to perform, but one of the police inspectors has told me
that he himself caught a coast-guardsman in the act of thieving.
Friends and relatives complain that there is more anxiety to
discover gold than bodies; but the fact is no gold has as yet
been discovered by the divers. They recommenced operations at
ten o’clock this morning, but have brought up nothing but
copper bars. Fathers, mothers, wives, children, and other
relatives pace the beach from an early hour in the morning.
Yesterday delicate women braved the rain and storm all day,
making their melancholy search. Every now and then I was met
by persons with sorrowful faces, one inquiring, “Have you seen
any trace of my husband? his name was ——;” or “Have you
found anything with the name of ——? she was my child.”
Indeed, it is a heartrending thing to go near the beach, and to
see these mourners, and to meet the carts carrying the
mangled corpses, or the parish coffins in which they are to be
interred. None of the bodies found last night have been
identified. Forty-five bodies have been discovered up to this
time.’
‘The “Royal Charter” was built about four years ago; she was of
2,719 tons register, and 200 horse power. Her owners were
Messrs. Gibb, Brights, and Co., of Liverpool. She was an iron
vessel, worked by a screw. On the 26th of August last she sailed
from Melbourne, having on board 388 passengers, and a crew,
including officers, of 112 persons. She accomplished her
passage in two months as near as may be. On Monday morning
she passed Queenstown, and thirteen of the passengers landed
in a pilot-boat. The next day the “Royal Charter” took on board
from a steam-tug eleven riggers who had been assisting in
working a ship to Cardiff. Thus, at the time of the calamity there
were on board 498 persons, and of these only 39 were saved.
The ship, as we are informed, had on board but a small cargo,
mainly of wool and skins. A more important item of her freight
was gold and specie, which at the lowest estimate is put at
500,000l. On Tuesday evening there was blowing from the
E.N.E. a violent gale, which fell with full force on the ill-fated
ship. She arrived off Point Lynas at six o’clock in the evening of
Tuesday, and for several hours Captain Taylor continued
throwing up signal rockets, in the hope of attracting the
attention of a pilot. None made his appearance. The gale
increased in violence; the ship was making leeway, and drifting
gradually towards the beach. It was pitch dark; no help was at
hand. The captain let go both anchors, but the gale had now
increased to a hurricane, and had lashed the sea up to
madness. The chains parted, and, notwithstanding that the
engines were worked at their full power, the “Royal Charter”
continued to drift towards the shore. At three A.M. she struck the
rocks in four fathoms of water. The passengers till this moment
had no idea of the imminence of their peril. The masts and
rigging were cut adrift, but this gave no relief. The ship
continued to grind and dash upon the rocks. The screw became
foul with the drift spars and rigging, and ceased to act. The
consequence was, that the ship was thrown broadside on to the
rocks, and now the terror began. The officers of the ship either
hoped against hope, or endeavoured to alleviate the agony of
the passengers by assuring them there was no immediate
danger. A Portuguese sailor, Joseph Rogers—his name deserves
to be recorded—volunteered to convey a rope on shore through
the heavy surf, and succeeded in his attempt. Had time been
given no doubt every person on board could now have been
safely conveyed on shore; but it was fated that the end should
be otherwise. One tremendous wave came after another,
playing with the “Royal Charter” like a toy, and swinging her
about on the rocks. She divided amidships, and wellnigh all on
board were swept into the furious sea. A few minutes
afterwards she also parted at the forehatch, and then there was
an end. Those who were not killed by the sea were killed by the
breaking up of the ship. In the course of a very few moments
the work was done, and four hundred and fifty-nine persons
were numbered among the dead. It was about seven A.M. on
Wednesday that she broke up.
‘It is said by those who have visited the scene of the calamity
that never was destruction more complete. The ironwork of the
vessel is in mere shreds; the woodwork is in chips. The coast
and the fields above the cliffs are strewn with fragments of the
cargo and of the bedding and clothing. In the words of one of
our reports, “A more complete annihilation of a noble vessel
never occurred on our coast.” Worse still, the rocks are covered
with corpses of men and women frightfully mutilated, and
strewn with the sovereigns which the poor creatures had gone
so far to seek, and which were now torn from them in so pitiful
a way. Of course, as is usual in all such cases, the reasons given
for the occurrence of the calamity are various. In one account
we see it attributed to the order given before midnight to veer
out on the starboard cable. This, as it is said, brought too much
strain upon the port cable, which parted, and then the other
parted also, and then the ship drifted ashore. Others tell us that
if the screw had not been fouled by the drift rigging and spars,
the “Royal Charter” might have been saved. These, however,
could have been but secondary and minor causes. The origin of
the calamity seems to have been that in a wild night, with a
gale blowing that soon became a hurricane, the ship was
brought up dangerously near a lee shore. Let it be remembered,
however, that Captain Taylor was the last man seen alive on
board.’
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
textbookfull.com