0% found this document useful (0 votes)
10 views

102847

The document promotes the availability of various editions of 'The Rust Programming Language' and other related Rust programming ebooks for download at textbookfull.com. It includes links to specific titles and emphasizes the convenience of accessing digital formats like PDF, ePub, and MOBI. Additionally, it provides information about the authors and technical reviewers involved in the creation of the book.

Uploaded by

denoxpostai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

102847

The document promotes the availability of various editions of 'The Rust Programming Language' and other related Rust programming ebooks for download at textbookfull.com. It includes links to specific titles and emphasizes the convenience of accessing digital formats like PDF, ePub, and MOBI. Additionally, it provides information about the authors and technical reviewers involved in the creation of the book.

Uploaded by

denoxpostai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 67

Explore the full ebook collection and download it now at textbookfull.

com

The Rust Programming Language 2nd Edition Steve


Klabnik

https://textbookfull.com/product/the-rust-programming-
language-2nd-edition-steve-klabnik/

OR CLICK HERE

DOWLOAD EBOOK

Browse and Get More Ebook Downloads Instantly at https://textbookfull.com


Click here to visit textbookfull.com and download textbook now
Your digital treasures (PDF, ePub, MOBI) await
Download instantly and pick your perfect format...

Read anywhere, anytime, on any device!

The Rust Programming Language Covers Rust 2018 Steve


Klabnik

https://textbookfull.com/product/the-rust-programming-language-covers-
rust-2018-steve-klabnik/

textbookfull.com

The Rust Programming Language 1st Edition Steve Klabnik

https://textbookfull.com/product/the-rust-programming-language-1st-
edition-steve-klabnik/

textbookfull.com

The Rust Programming Language 2nd Edition Steve Klabnik


And Carol Nichols

https://textbookfull.com/product/the-rust-programming-language-2nd-
edition-steve-klabnik-and-carol-nichols/

textbookfull.com

Programming Rust, 2nd Edition (Early Release) Jim Blandy

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

The Complete Rust Programming Reference Guide Rahul Sharma

https://textbookfull.com/product/the-complete-rust-programming-
reference-guide-rahul-sharma/

textbookfull.com

Programming WebAssembly with Rust 1st Edition Kevin


Hoffman

https://textbookfull.com/product/programming-webassembly-with-
rust-1st-edition-kevin-hoffman/

textbookfull.com

Network Programming With Rust 1st Edition Abhishek Chanda

https://textbookfull.com/product/network-programming-with-rust-1st-
edition-abhishek-chanda/

textbookfull.com

Asynchronous Programming in Rust 1st Edition Carl Fredrik


Samson

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

ISBN-13: 978-1-7185-0310-6 (print)


ISBN-13: 978-1-7185-0311-3 (ebook)

Publisher: William Pollock


Managing Editor: Jill Franklin
Production Manager: Sabrina Plomitallo-González
Production Editors: Jennifer Kepler and Katrina Horlbeck Olsen
Developmental Editor: Liz Chadwick
Cover Illustration: Karen Rustad Tölva
Interior Design: Octopod Studios
Technical Reviewer: JT
Copyeditor: Audrey Doyle
Compositor: Jeff Lytle, Happenstance Type-O-Rama
Proofreader: Liz Wheeler
The Library of Congress has catalogued the first edition as follows:

Names: Klabnik, Steve, author. | Nichols, Carol, 1983- eauthor.


Title: The Rust programming language / by Steve Klabnik and Carol Nichols ; with contributions from
the Rust Community.
Description: San Francisco : No Starch Press, Inc., 2018. | Includes index. Identifiers: LCCN
2018014097 (print) | LCCN 2018019844 (ebook) | ISBN 9781593278519 (epub) | ISBN 1593278519 (epub)
| ISBN 9781593278281 (paperback) | ISBN 1593278284 (paperback)
Subjects: LCSH: Rust (Computer programming language) | BISAC: COMPUTERS / Programming / Open Source.
| COMPUTERS / Programming Languages / General. | COMPUTERS / Programming / General.
Classification: LCC QA76.73.R87 (ebook) | LCC QA76.73.R87 K53 2018 (print) | DDC 005.13/3--dc23
LC record available at https://lccn.loc.gov/2018014097

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.

About the Technical Reviewer


JT is a Rust core team member and the co-creator of the Rust error message
format, Rust Language Server (RLS), and Nushell. They first started using
Rust in 2011, and in 2016 joined Mozilla to work on Rust full-time, helping
to shape its direction for widespread use. These days, they are a freelance
Rust trainer and advocate for safe systems programming.
BRIEF CONTENTS

Foreword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xix

Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxi

Acknowledgments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxiii

Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxv

Chapter 1: Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

Chapter 2: Programming a Guessing Game . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

Chapter 3: Common Programming Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31

Chapter 4: Understanding Ownership . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59

Chapter 5: Using Structs to Structure Related Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85

Chapter 6: Enums and Pattern Matching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103

Chapter 7: Managing Growing Projects with Packages, Crates, and Modules . . . . . . . . . . 119

Chapter 8: Common Collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141

Chapter 9: Error Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161

Chapter 10: Generic Types, Traits, and Lifetimes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181

Chapter 11: Writing Automated Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215

Chapter 12: An I/O Project: Building a Command Line Program . . . . . . . . . . . . . . . . . . . 243

Chapter 13: Functional Language Features: Iterators and Closures . . . . . . . . . . . . . . . . . . 273

Chapter 14: More About Cargo and Crates.io . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295

Chapter 15: Smart Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315

Chapter 16: Fearless Concurrency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353

Chapter 17: Object-Oriented Programming Features . . . . . . . . . . . . . . . . . . . . . . . . . . . 375

Chapter 18: Patterns and Matching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397


Chapter 19: Advanced Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 419

Chapter 20: Final Project: Building a Multithreaded Web Server . . . . . . . . . . . . . . . . . . . 459

Appendix A: Keywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 495

Appendix B: Operators and Symbols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 499

Appendix C: Derivable Traits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 507

Appendix D: Useful Development Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 511

Appendix E: Editions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 515

Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 517

viii Brief Contents


CO N T E N T S I N D E TA I L

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

xii Contents in Detail


Traits as Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
Returning Types That Implement Traits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199
Using Trait Bounds to Conditionally Implement Methods . . . . . . . . . . . . . . . . 200
Validating References with Lifetimes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
Preventing Dangling References with Lifetimes . . . . . . . . . . . . . . . . . . . . . . . 201
The Borrow Checker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202
Generic Lifetimes in Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
Lifetime Annotation Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
Lifetime Annotations in Function Signatures . . . . . . . . . . . . . . . . . . . . . . . . . 205
Thinking in Terms of Lifetimes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208
Lifetime Annotations in Struct Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
Lifetime Elision . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
Lifetime Annotations in Method Definitions . . . . . . . . . . . . . . . . . . . . . . . . . 212
The Static Lifetime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212
Generic Type Parameters, Trait Bounds, and Lifetimes Together . . . . . . . . . . . . . . . . . . 213
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213

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

Contents in Detail xiii


Working with Environment Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265
Writing a Failing Test for the Case-Insensitive Search Function . . . . . . . . . . . . 265
Implementing the search_case_insensitive Function . . . . . . . . . . . . . . . . . . . . 266
Writing Error Messages to Standard Error Instead of Standard Output . . . . . . . . . . . . . 270
Checking Where Errors Are Written . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270
Printing Errors to Standard Error . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272

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

xiv Contents in Detail


Treating Smart Pointers Like Regular References with Deref . . . . . . . . . . . . . . . . . . . . . 321
Following the Pointer to the Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322
Using Box<T> Like a Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323
Defining Our Own Smart Pointer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323
Implementing the Deref Trait . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324
Implicit Deref Coercions with Functions and Methods . . . . . . . . . . . . . . . . . . 325
How Deref Coercion Interacts with Mutability . . . . . . . . . . . . . . . . . . . . . . . 326
Running Code on Cleanup with the Drop Trait . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327
Rc<T>, the Reference Counted Smart Pointer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330
Using Rc<T> to Share Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331
Cloning an Rc<T> Increases the Reference Count . . . . . . . . . . . . . . . . . . . . . 333
RefCell<T> and the Interior Mutability Pattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334
Enforcing Borrowing Rules at Runtime with RefCell<T> . . . . . . . . . . . . . . . . . 334
Interior Mutability: A Mutable Borrow to an Immutable Value . . . . . . . . . . . . . 335
Allowing Multiple Owners of Mutable Data with Rc<T> and RefCell<T> . . . . . 342
Reference Cycles Can Leak Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343
Creating a Reference Cycle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343
Preventing Reference Cycles Using Weak<T> . . . . . . . . . . . . . . . . . . . . . . . 346
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351

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

xvi Contents in Detail


Macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 449
The Difference Between Macros and Functions . . . . . . . . . . . . . . . . . . . . . . . 449
Declarative Macros with macro_rules! for General Metaprogramming . . . . . . 449
Procedural Macros for Generating Code from Attributes . . . . . . . . . . . . . . . . 451
How to Write a Custom derive Macro . . . . . . . . . . . . . . . . . . . . . . . . . . . . 452
Attribute-Like Macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 457
Function-Like Macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 458
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 458

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

Contents in Detail xvii


D
USEFUL DEVELOPMENT TOOLS 511
Automatic Formatting with rustfmt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 511
Fix Your Code with rustfix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 512
More Lints with Clippy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 513
IDE Integration Using rust-analyzer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 514

E
EDITIONS 515

INDEX 517

xviii Contents in Detail


FORE WORD

It wasn’t always so clear, but the Rust programming language is fundamen-


tally about empowerment: no matter what kind of code you are writing now,
Rust empowers you to reach further, to program with confidence in a wider
variety of domains than you did before.
Take, for example, “systems-level” work that deals with low-level details of
memory management, data representation, and concurrency. Traditionally,
this realm of programming is seen as arcane, accessible to only a select few
who have devoted the necessary years to learning it to avoid its infamous
pitfalls. And even those who practice it do so with caution, lest their code be
open to exploits, crashes, or corruption.
Rust breaks down these barriers by eliminating the old pitfalls and provid-
ing a friendly, polished set of tools to help you along the way. Programmers
who need to “dip down” into lower-level control can do so with Rust, without
taking on the customary risk of crashes or security holes and without hav-
ing to learn the fine points of a fickle toolchain. Better yet, the language is
designed to guide you naturally toward reliable code that is efficient in terms
of speed and memory usage.
Programmers who are already working with low-level code can use
Rust to raise their ambitions. For example, introducing parallelism in Rust
is a relatively low-risk operation: the compiler will catch the classical mis-
takes for you. And you can tackle more aggressive optimizations in your
code with the confidence that you won’t accidentally introduce crashes or
vulnerabilities.
But Rust isn’t limited to low-level systems programming. It’s expressive
and ergonomic enough to make CLI apps, web servers, and many other
kinds of code quite pleasant to write—you’ll find simple examples later in
the book. Working with Rust allows you to build skills that transfer from
one domain to another; you can learn Rust by writing a web app, then apply
those same skills to target your Raspberry Pi.
This book fully embraces the potential of Rust to empower its users.
It’s a friendly and approachable text intended to help you level up not just
your knowledge of Rust, but also your reach and confidence as a program-
mer in general. So dive in, get ready to learn—and welcome to the Rust
community!

Nicholas Matsakis and Aaron Turon

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:

• Chapter 7 contains a new quick reference section on organizing your


code into multiple files with modules.
• Chapter 13 has new and improved closure examples that more clearly
illustrate captures, the move keyword, and the Fn traits.
• We fixed a number of small errors and imprecise wording throughout
the book. Thank you to the readers who reported them!

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

Welcome to The Rust Programming Language,


an introductory book about Rust. The
Rust programming language helps you
write faster, more reliable software. High-level
ergonomics and low-level control are often at odds
in programming language design; Rust challenges
that conflict. Through balancing powerful techni-
cal capacity and a great developer experience, Rust
gives you the option to control low-level details (such
as memory usage) without all the hassle traditionally
associated with such control.
Who Rust Is For
Rust is ideal for many people for a variety of reasons. Let’s look at a few of
the most important groups.

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.

People Who Value Speed and Stability


Rust is for people who crave speed and stability in a language. By speed, we
mean both how quickly Rust code can run and the speed at which Rust lets
you write programs. The Rust compiler’s checks ensure stability through
feature additions and refactoring. This is in contrast to the brittle legacy
code in languages without these checks, which developers are often afraid
to modify. By striving for zero-cost abstractions—higher-level features that
compile to lower-level code as fast as code written manually—Rust endeav-
ors to make safe code be fast code as well.
The Rust language hopes to support many other users as well; those
mentioned here are merely some of the biggest stakeholders. Overall, Rust’s
greatest ambition is to eliminate the trade-offs that programmers have
accepted for decades by providing safety and productivity, speed and ergo-
nomics. Give Rust a try and see if its choices work for you.

Who This Book Is For


This book assumes that you’ve written code in another programming lan-
guage, but doesn’t make any assumptions about which one. We’ve tried to
make the material broadly accessible to those from a wide variety of pro-
gramming backgrounds. We don’t spend a lot of time talking about what
programming is or how to think about it. If you’re entirely new to program-
ming, you would be better served by reading a book that specifically provides
an introduction to programming.

How to Use This Book


In general, this book assumes that you’re reading it in sequence from front
to back. Later chapters build on concepts in earlier chapters, and earlier
chapters might not delve into details on a particular topic but will revisit the
topic in a later chapter.
You’ll find two kinds of chapters in this book: concept chapters and
project chapters. In concept chapters, you’ll learn about an aspect of Rust.
In project chapters, we’ll build small programs together, applying what
you’ve learned so far. Chapter 2, Chapter 12, and Chapter 20 are project
chapters; the rest are concept chapters.
Chapter 1 explains how to install Rust, how to write a “Hello, world!”
program, and how to use Cargo, Rust’s package manager and build tool.
Chapter 2 is a hands-on introduction to writing a program in Rust, having
you build up a number-guessing game. Here, we cover concepts at a high
level, and later chapters will provide additional detail. If you want to get

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.

‘He says he was in bed in a berth with four other passengers


when the ship struck, and he was aroused by one of his
comrades exclaiming, “I think we’re lost.” He dressed himself,
and after a few minutes’ prayer, ascended on deck, where he
had not been more than a very brief period when the vessel
parted in the centre “like the snapping of a tobacco stump.” The
people on board stood petrified, as it were, seemingly unable to
make the slightest struggle for their lives; whilst their terror was
increased by the awful scenes presented as unfortunate
creatures fell and were crushed to atoms in the chasm
separating the two parts of the ship. He never for a moment
lost his presence of mind. He saw that most of those in the
water struggled towards the large pieces of the wreck, and he
saw also that most of those who trusted to these heavy portions
of the vessel were crushed to death, and their bodies dreadfully
mutilated against the rocks. Though totally unable to swim he
jumped overboard, and just seized a box he saw floating near
him. Almost at the very moment he seized this a head was
thrust under his arm, and a second claimant appeared. Dean
said it would not support both of them; so as soon as possible
he left the box for another piece of wood, and with this he was
thrown upon the shore. He left his support and tried to gain a
position of security; but ere he could do so a wave overpowered
him and carried him back to sea, where he became entangled in
the floating remnants of the vessel, and it was with the greatest
difficulty that he extricated himself. When he had succeeded in
this, he was again thrown on shore. Whilst momentarily
expecting the arrival of another wave, a rope was thrown to
him, and by it he was finally drawn out of danger, without
experiencing any injuries or bruises other than of a very trifling
description. He soon recovered strength. He was bringing home
a cheque for a considerable sum of money, and before his
voyage he had taken the precaution to enclose this in a
waterproof belt, which he kept around his waist. This cheque is
therefore saved, and his only losses are his clothes and a small
sum of money which was with them.’

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:—

‘We sailed from Melbourne on the 26th of August, and had on


board, as I know, about five hundred passengers and crew. The
captain was Mr. Thomas Taylor; the chief officer, Mr. Stevens;
and the second mate, Mr. Cowie. The ship ran almost entirely
under canvas up to the equinoctial line, when she encountered
strong head winds. Her screw power was then brought into
requisition. On the 10th of September, about four o’clock in the
morning, the weather being thick and dark, we ran close past a
large iceberg. Mr. Cowie was on watch, and had it not been for
his able manœuvring, the ship would have been in imminent
danger. The passengers showed their appreciation of his ability
by presenting him with a testimonial on the eve of the dreadful
disaster. We arrived at Queenstown on Monday forenoon, when
twelve passengers disembarked. We left Queenstown about two
o’clock, under steam alone. The ship was laid on her course for
Liverpool, but the storm had the effect of diverting her to such
an extent that I saw the “Great Eastern” at Holyhead. The wind
was then blowing very hard. We sighted the light on Point Lynas
about five o’clock in the afternoon. The sea was running high,
though not equal to what we had experienced on the passage;
but the wind was stronger. It was found we could make no
headway, and two anchors were dropped. She dragged her
anchors, and the engines were working, but I understood the
screw was broken.
‘About two o’clock on Wednesday morning the vessel struck. A
great number of passengers were then in their berths; but they
suddenly rushed upon deck, many of them but partially dressed.
There was not much confusion at first, but it increased as
people became aware of the real danger. I believe the captain
was not sober; but Captain Withers, who was a passenger, and
the chief mate and officers, did all they could to save the ship. A
rope was got out from the head of the vessel, but I cannot say
how. A kind of rope chain was made and placed upon it. By
means of this some were drawn along the hawser to the shore.
When the rope was seen there was a great rush to the
forecastle deck, in order to get the first advantage. A large wave
washed over her head and carried them into the sea. Others
followed, but only to meet a similar fate. I was standing near
the davit of a boat on the poop, when a sea jammed me fast
between the boat and something else. I was beaten about and
my ankle dislocated, and then my leg was broken. I then
became insensible for a short time, but on regaining my
consciousness I got a rope, and fastening it, lowered myself
down from the poop into the sea, upon a piece of the wreck,
along with the storekeeper. I was knocked up and down, turned
topsy turvy, driven and battered against this thing and the other
till I lighted upon a piece of cabin framework, and paddled
myself along with my hands. The waves washed me three times
on the rocks, and took me back, battering me about. The next
time I fell between two rocks, which held me, and I was picked
up by two men. Four men brought me to this house, which is
kept by Mr. Owens; who has been very kind to me. My leg was
set by Mr. Thomas of Liverpool.’

The simplicity of that statement must touch the strongest. Captain


Withers, it may be worth mentioning, was returning from Australia,
after having lost his ship in the Pacific. His exertions throughout the
storm were very great, and it was under his advice that the masts
were cut away.[C] There are those who say that if the ship had been
earlier dismasted she would not have gone to pieces. I can speak
with no authority upon this point. This, however, I know, Captain
Taylor so loved his craft that when we ran short of provisions coming
home, and might, with two or three hours’ supply more of fuel have
made the Island of St. Vincent, and taken in a stock both of firing
and food, he preferred running all the hazard of ‘keeping on,’ rather
than touch the ‘beautiful spars’ of his vessel. The loss to his owners
in consequence was many thousand pounds. In compensation to
second and third class passengers alone, they had to pay something
like fifteen hundred pounds. I can, therefore, readily understand that
the dismasting of the vessel may have been unfortunately delayed
until it was too late to save her. At the same time it is but fair to the
memory of the captain—than whom a braver sailor never trod a deck
—to say that all such rumours should be accepted with caution.
Colonial readers will well remember the many absurd and
contradictory reports which were current when the ‘Dunbar’ went
ashore.
[C] The following appears in the Morning Herald of November
2nd:—‘Captain Withers, the master of the wrecked vessel
“Virginia” (lost in the South Pacific), with nine men, after being
nineteen days at sea in an open boat, and enduring innumerable
privations, all arrived safe at the Feejee islands, and thence they
were conveyed to Sydney, New South Wales. On arriving at
Sydney, Captain Withers after seeing that the crew were provided
with clothes, went on to Melbourne, and took a passage home to
England in the “Royal Charter.” He is the “Captain Withers”
mentioned by one of the persons saved from the wreck of the
“Royal Charter,” who behaved with such noble fortitude and
unflinching bravery when all seemed lost, and when it was a
mockery to hope against such a fearful tempest. But he was
doomed to die a sailor’s death, for the last seen of him was when
he called out to Mr. Stevens and Captain Taylor, “God bless you,
Stevens! God bless you, Taylor! Keep firm.” The ship broke up
immediately after: the rest already too well known.’ Strange are
the ways of Providence! Captain Withers was saved, after terrible
privations, from perishing in the South Pacific to be dashed to
pieces on the rocks of Wales! [Back to text]

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:—

‘Molfra Bay, Thursday Evening.—It is my very painful duty to


record the total wreck of the screw steamship “Royal Charter,”
Captain Taylor, which took place at from three to eight o’clock
on the morning of Wednesday, at Molfre, a rugged portion of
the Anglesea coast, and about midway between Amlwch and
Ruffin Island. The ill-fated vessel sailed from Melbourne on the
26th of August, having on board 388 passengers, of whom 63
occupied the saloon, and a crew, including officers, of 112
persons. While the ship was passing Queenstown, on Monday
morning, 13 of the passengers landed in a pilot-boat. On
Tuesday morning, at eleven o’clock, the “Royal Charter” spoke
the steam-tug “United Kingdom,” which, instead of returning to
port with riggers who had been assisting in the working of a
ship to Cardiff, transferred 11 of the riggers to the “Royal
Charter,” Captain Taylor having kindly agreed to take them to
Liverpool; so that there were on board at the time of the wreck
498 souls, and of these only 39 were saved.
‘The loss of life on this sad occasion was 459 persons. The
“Royal Charter” had on board a large quantity of specie on
freight, the exact amount of which cannot be ascertained, as all
the ship’s papers have been lost, but it was variously estimated
by the surviving passengers and crew at from 500,000l. to
800,000l. One of the saloon passengers, who was drowned, was
stated to have had in his possession gold to the value of
10,000l. She had only a moderate cargo, principally of wool and
skins.’ [Did the small cargo have anything to do with the loss of
the vessel? Would she, if more heavily laden, have drifted so
rapidly upon the rocks?] ‘From the time of leaving Port Phillip
Heads till the arrival off the Irish coast the passage was in the
highest degree favourable; she was only once in danger, and
then from an iceberg. After passing Queenstown the wind
veered round to E.N.E., blowing strong. On Tuesday night it
blew a gale, and continued to increase in violence, till at length,
on the morning of the fatal disaster, it became a perfect
hurricane. Arriving off Point Lynas at six P.M. on Tuesday
evening, signal rockets were for several hours thrown up, in the
hope of attracting a pilot, but none made their appearance.
Captain Taylor, finding that his ship was making leeway, and
gradually drifting towards the shore, let go both the anchors,
but such was the violence of the wind, and the heavy cross sea
prevailing, that the chains parted.’ [The same night the “Great
Eastern” was all but lost through one of her massive cables
snapping.] ‘Notwithstanding that the engines were worked at
their full power, the captain was unable to work to windward,
and the unfortunate vessel struck the rocks stern first in four
fathoms water. Up to this period (about three A.M.) not the
slightest alarm was evinced among the passengers, a large
portion of whom were women and children. The most perfect
discipline and order prevailed. The masts and rigging were cut
adrift, but caused no relief, as the ship continued to thump on
the sharp-pointed rocks with fearful rapidity.
‘Shortly after she struck, the ship was thrown broadside on,
perfectly upright upon the shelving stony beach, the head and
stern lying due east and west, the former not being more than
twenty yards from a projecting rock. At this juncture one of the
crew, a Maltese, named Joseph Rogers, nobly volunteered to
struggle through the heavy surf and convey a rope on shore.
Though it was not believed by any one that danger was
imminent, the captain gave the order, and Rogers ably fulfilled
his duty. A strong hawser was then passed and secured on
shore, and to this was rigged a “boatswain’s chair.” At five
o’clock the ship laboured and bumped to such an extent that
the ladies and children exhibited the greatest anxiety and fear:
they crowded together in the after part of the saloon, and the
Rev. Mr. Hodge, of East Retford, a Clergyman of the Church of
England, offered up a prayer; but his exhortations were
interrupted by the violent thumping of the vessel on the rocks,
and the heavy seas which came dashing into the cabin.’
[Throughout the passage, this reverend gentleman had
administered religious service, and had made so many
friendships that his fellow-passengers had presented him with a
testimonial.] ‘The scene in the saloon was of the most
heartrending description; children and parents, husbands and
wives, were clinging to each other in affectionate embrace.
Captain Taylor and Captain Withers came down and tried to
allay their fears by assuring them that there was no immediate
danger. Scarcely had their words been uttered before a
succession of tremendous waves swung her about on the rocks,
and she divided amidships, engulfing all on board. Shortly
afterwards she also parted at the forehatch, throwing a large
number of persons into the sea. Many were killed by the
breaking up of the ship. Several of the crew saved themselves
by means of the hawser to the shore, while the remainder were
hurled upon the rocks by the waves. All the officers perished.
Captain Taylor was the last man seen alive on board. He had
lashed his body to a spar and was drowned.’ [Some affirm he
was killed, after he was in the sea, by a boat falling from its
davits. It is said he and Mr. Cowie, the second officer, were seen
together, and that the boat struck both at once. Mr. Stevens, the
first officer, and Mr. Rogers, the chief engineer, were—runs the
main body of testimony—also killed together by the falling of a
suspended boat upon the deck.] ‘Mr. Stevens, the chief officer,
was killed, it is thought, by the falling rigging. Several of the
more fortunate passengers received severe injuries while
struggling for life. With the exception of a portion of the midship
bulkhead, which appears a few feet above the water, there is
scarcely a vestige of the “Royal Charter” remaining. The bullion
chest, which was substantially built of iron, and secured to the
framing of the ship, is supposed to have been shattered, from
the fact of a gold box having been picked up with the address of
a leading banking firm upon it.’ [The subsequent operations of
the divers have, up to the time I am writing, tended to confirm
this hypothesis, although assurances at fifty, sixty, and eighty
per cent. are still being effected at Lloyd’s.]
‘About two hundred and fifty sovereigns and a quantity of notes
had been picked up among the rocks.
‘At least thirty bodies which have been cast ashore are lying in
the adjacent church; most of them are frightfully mutilated.
William Hughes, the only apprentice saved, states that when the
vessel parted he was in the waist, and was precipitated among
the machinery, which was hurled to and fro by the action of the
waves. He had given himself up for lost, when a wave lifted him
clear of the ship, and landed him in an unconscious state. The
survivors during their stay at the scene of the wreck were very
kindly treated. Two ladies made themselves conspicuous by
their attention to the sufferers. It is stated that all the boats
were in perfect readiness for lowering had circumstances
permitted.’ [Some of the passengers say the boats were
launched, and were dashed to pieces on the rocks.]

The second correspondent’s letter is equally interesting. Of course a


number of persons describing one event will, as has been often
pointed out, fall into discrepancies of statement. It is not for me to
make the reports uniform. I have thrown in a parenthetical
explanation here and there; but otherwise the several newspapers
must speak for, and explain, themselves. The second communication
runs thus:—
‘The “Royal Charter” did not, as was at first stated, strike the
ground in Red Wharf Bay, but a place between that point and
Amlwch. It is a small opening in the coast, the beach being
chiefly sand and stones. It is to the west of Point Lynas, and
known as Molfra, a village in the immediate locality, being of
that name. The coast is thinly inhabited, and the land flat and
uncultivated. Very soon after the fatal catastrophe, which
resulted in such an awful sacrifice of human life, the vessel
broke up, and nothing remains but pieces of the wreck, which
were moved to and fro by the action of the tide. As one of the
seamen described it, she broke up like a bandbox.
‘Those of the crew and passengers who escaped were provided
with temporary accommodation in the neighbouring cottages,
where they received every mark of kindness from the
inhabitants. During the day most of them left the place, and
were conveyed to Liverpool in steam-tugs sent out by the
owners of the ship.’ [And were, it is said, shamefully treated
after their arrival. But of this in time.] ‘Last (Friday) evening only
one passenger remained, Mr. Russell, with the boatswain’s mate
and the carpenter of the ship. Many persons visited the scene of
the wreck yesterday, and were making anxious inquiries as to
the fate of relatives and friends. For this purpose every facility
was afforded. Some of the scenes arising out of these inquiries
amongst those deprived of their nearest relatives and friends
were affecting in the extreme. Shortly after the wreck several of
the bodies of the unfortunate sufferers by the calamity floated
upon the beach; subsequently others were picked up, and the
number amounted at a late hour last evening to twenty-six. Of
these, five were females, and two of them young children. The
bodies were conveyed to Llanallgo church, and carefully laid out
on straw, so as to afford an opportunity for identification. Some
had on their clothing, while others were only partially dressed,
as though when the vessel struck they had been in their berths,
and rushed suddenly to the deck in a state of alarm on being
made acquainted with the perilous position of the ship. Many of
the bodies bore evidence of injuries, probably sustained from
being dashed against the rocks, or coming into violent contact
with portions of the wreck. One man had nearly all his limbs
broken, and the body had, as it were, to be gathered up.
Another was without the head, and several were much bruised
on various parts of the body. Some small boats and papers were
picked up yesterday on the beach. One of the papers appeared
to be a diary kept by a passenger on board, supposed to be a
clergyman of Nottingham. The various incidents of the voyage,
from the time of leaving Melbourne until the arrival at
Queenstown, were carefully recorded by the writer.’ [This is
doubtless Mr. Hodge, a good man who would keep a diary.] ‘The
riggers previously referred to as being on board the “Royal
Charter” when she grounded have lost six of their number,
namely, James O’Neill, Richard Morris, William Thomas, Peter
Topping, Thomas Corcoran, and Henry White. Those saved are
James White, Patrick Devine, —— Pritchard, Thomas
Cunningham, and William Burton. Some of them swam ashore,
and others succeeded in saving themselves by the aid of the
hawser. So far none of the passengers’ luggage or articles of a
similar kind have been washed on shore.’ [Much was afterwards
found, as will be seen.] ‘A few articles of male and female attire
have been collected, and these are taken care of by the officers
of police and coast-guard now on duty. The services of the
Anglesea militia have also been called into requisition, to assist
in the protection of any property received, and also in the
removal of the bodies washed up on the shore. The position of
the vessel at the time of the catastrophe, and whether or not
blame attaches to the captain or his officers, were subjects of
comment amongst many of those who visited the spot
yesterday. At present it would be unfair to give currency to
these remarks, seeing that the matter will undergo a strict
investigation at the coroner’s inquest. The number of persons
saved is now stated to be thirty-nine; and of these, twenty-one
are passengers, and the remainder belong to the crew. Only
very few of the bodies recovered have yet been identified. A
gentleman attended yesterday, to make inquiry as to his wife,
whom he supposed to be on board the “Royal Charter.” The
body of his beloved partner was not amongst those lying in the
church, but on a closer investigation, his eye fell on the corpse
of a faithful servant, who, he felt sure, would accompany his
wife on the voyage. This fact too truly told the mournful result.
‘The man who swam on shore with the hawser was a Maltese,
and not a Portuguese, as first said. He lost everything he
possessed, and swooned when he reached land.’

Depend upon it that man (“heroism has no country”) will be


rewarded. We shall not do here as was done in Sydney when the
‘Dunbar’ was lost,—allow our sympathy to expend itself upon the
saved to the all but utter forgetfulness of the saviour.
A third and a later newspaper reporter’s letter must find a place:—

‘Molfra Village, Redwharf Bay, Saturday.—Who does not shudder


at the mention of a shipwreck? In Llanallgo church, about a mile
from the desolate coast on which the unfortunate “Royal
Charter” has gone on shore, lie about thirty distorted and
mangled bodies, and to that locality anxious and distracted
relatives crowded early yesterday morning. At another church
hard by, which is known as Penrhos, there were also the bodies
of two children and two ladies laid out; and the anxiety of
friends may be gathered when it is stated that through pelting
and incessant rain, over almost inaccessible roads, for more
than fifteen miles, hundreds of people wended their way to the
locus in quo of the wreck.
‘This has been pronounced the most dreadful occurrence of the
kind that has happened on this coast. Perhaps it is the most
terrible marine disaster that has ever happened anywhere. So
complete is the wreck, that Captain Fell says in his naïve
nautical style, that he has been seventeen years “at this sort of
work,” but never saw a vessel so completely destroyed. The size
of the ship, too, and the number of persons lost, render it an
unexampled calamity.
‘Captain Fell, from Lloyd’s, was in attendance early yesterday
(Friday) morning, at Molfra or Moelfra, deputed to make
inquiries for the underwriters. The vessel had on board 49,000l.
in specie, 79,000 oz. in gold, valued at 320,000l., making a total
of 369,000l., besides a large quantity of money in the hands of
the passengers. The excitement at Lloyd’s on the arrival of the
disastrous intelligence is described by Captain Fell as intense,
the confidence from the first in the ship’s sailing qualities being
so great that insurances were taken at 80s. per cent. As an
indication of the wealth in the hands of the crew and
passengers, it may be mentioned that torn and dilapidated
garments have been picked up on the shore, some of which
contain considerable amounts of money, watches, and other
valuables. Intimation was early given of the danger in which the
ship was placed, but though little hope was entertained of the
safety of the vessel herself, every one seems to have retained a
hope of life, and rushed to his and her valuables and money,
and sought safety with as little encumbrance in the shape of
clothing as possible.’

And yet another communication, though only of a few lines, must be


given. It were easy to write a most pathetic prolusion to it, but I
prefer to let it stand in its nude significance:—

‘Liverpool, Sunday Morning.—This banquet (that is, a Grand


Conservative Banquet to the Earl of Derby and Mr. Disraeli),
which during the last two months has been anticipated with so
much interest by the whole Conservative party, is just
concluded.... Altogether the general effect was remarkably
brilliant and picturesque. It ought to be remarked, however, that
many persons of position were absent on account of the wreck
of the “Royal Charter.” The calamity has cast a perceptible
gloom over the town, and at the beginning of the banquet the
conversation rather turned on the catastrophe than on politics.
Some thought the banquet ought never to have been held; but
the news of the accident arriving so near the day, it was
impossible to delay it: otherwise there is no doubt it would have
been postponed.’

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:—

‘The Inquest.—The inquest on the bodies was commenced


yesterday (Friday) afternoon, at Llanallgo church, before Mr.
William Jones, coroner of Anglesea, and a jury who were sworn
in Welsh. It was an impressive sight when the coroner, standing
at the communion table, surrounded by the group of dead and
mangled corpses, amid the audible sobs of those who had
recognized their friends, commenced his melancholy task.
‘Mr. Moore, solicitor of Warrington, before the opening of the
inquest, asked the coroner what course he intended to pursue.
‘The coroner thought he should be satisfied, under the
melancholy circumstances, with the identification of the bodies.
‘Mr. Bright, of the company owning the vessel, undertook to
have any of the surviving crew present who would be able to
give any information.
‘Mr. James Russell, who said his father lived in Linlithgowshire,
and who was one of the passengers who escaped, recognized
John Smith, son of Edmund Smith, Mrs. Woodroff (companion
to Mrs. Forster, also in the vessel and lost), Catherine Margaret
Russell, and Richard Reed. Mr. Forster lives at Grindlow House,
Manchester, Mrs. Woodroff’s husband is expected home by the
“George Marshall.” Richard Walton, of 22 Duckworth Street,
Brunswick Road, Liverpool, identified his brother James,
between 21 and 22. Thomas Outerside, 6 Clare Street,
Liverpool, printer, identified John Emery, Stone, Staffordshire.
‘The coroner then proceeded to Penrhos church, where he also
charged the jury with the investigation into the circumstances of
the death of the bodies lying there. The inquests were
adjourned until Wednesday.’ [Later proceedings before the
coroner, will be found elsewhere.] ‘In reply to an application, the
coroner undertook to have an interpreter provided.
‘Several parties were present who stated they were prepared to
vindicate the character and memory of Captain Taylor. The
vessel it was stated, made no water until it broke up. The ladies
it was arranged, should go first; but before opening the saloon
doors, the vessel parted in two and stopped all communication.
‘Mr. Samuel Henry, a jeweller from Adelaide, who had been
confined on the ground that he was insane, was amongst the
number in Llanallgo church. Mr. Glover, a gentleman of fortune
(from Adelaide, it is said), who was coming to England for the
purpose of consulting some skilled oculist, is also amongst the
number, and a large sum of money was found on his person.
Writing-desks, likenesses, letters, a part of the post-office, and
various other relics, have been washed up.’

The touching allusion to the likenesses and letters leads naturally to


the following (further) particulars from the scene of the calamity:—
‘Molfra Bay, Tuesday, Nov. the 2nd.—It is necessary that the
public should be on their guard against the rumours in
circulation as to the discoveries made by the divers who
commenced operations on Sunday. It was reported as an
established fact in Bangor last night that one of the divers had
entered the saloon of the “Royal Charter,” and there found about
200 passengers in the positions they occupied when the ship
went down; some sitting round the table, others standing
upright, and others as if in the act of coming from their berths.
A similar story was told some six or seven years ago, after the
wreck of a large steamer off the Bailey Light, Hill of Howth.
Indeed, in that case, the diver was made to describe some of
the passengers as in the act of lifting glasses to their mouths.
The lie was printed, and obtained very general circulation before
it was contradicted. The less detailed account is in the present
case equally destitute of foundation. Two experienced divers,
who came from Liverpool in the steam-tug “Fury,” the property
of Gibb, Brights, and Co., made a descent yesterday, and
remained a considerable time under the water, but they saw no
corpses beneath; neither did they find any gold; but they saw
some copper. This morning they resumed their descents under
very favourable circumstances as regards weather and the state
of the sea. They have discovered no bodies; but up to one
o’clock this afternoon they had succeeded, with the assistance
given them by men on board the steam-tug, in raising about
three tons of copper bars. These bars have undergone some
smelting, but are not in a finished state. There is a good deal of
silver mixed with the copper. At one o’clock the divers
suspended operations for a short rest and refreshment. They
resumed after about an hour’s interval.
‘Some additional articles of wearing apparel, with spars, etc.,
have been cast upon the beach. One or two canvas huts have
been erected on the remnants of masts, and in front of one of
these such articles as have names on them, or would otherwise
serve for purposes of identification, are spread out in
melancholy array. Amongst them are seven photographs, two of
men, two of ladies, two of children, and one landscape. None of
these have as yet been identified as portraits of individuals
whose friends have arrived at the scene of the wreck. There is a
stocking with the name “Jane Murray,” and another with the
name “F. Davis” upon it. There is a portion of a shirt, with the
name “J. E. Smith,” and another with the name “R. Thornhill,”
followed by the date “1846.” A large, coarse wrapper has the
inscription “C. R. Ross, passenger, ‘Royal Charter,’” painted in
black letters upon it. On a piece of a shirt, “E. Fenwick;” on
another, “John Lees, 1855.” On a piece of a stocking, “T. W.;”
and on a small piece of linen, “T. G.” There are a number of
visiting cards spread on a piece of wood: one has the
inscription, “Mr. Eddowes, 146 Cambridge-street, Pimlico;”
another, “Mr. Sam. Moxley Wade, Low, and Cill, Liverpool.” On a
piece of linen is “James Davis, Woodside, 1859.” The whole
scene of the wreck is an extremely melancholy one; but a
peculiarly affecting incident took place to-day. A poor young
woman was searching along the beach to endeavour to find
some trace of her husband, about whose fate she was
uncertain. She discovered a waistcoat which had just been
washed in, and which had been hung up in front of the tent by
one of the coast-guard. Almost frantically, she pulled it down. It
proved to be that of her husband, a man named Barrett, who
had been painter aboard the “Royal Charter.” The grief of the
poor widow was heartrending to witness. Some of the standers-
by, in an attempt to comfort her, suggested that she might be
mistaken. “Oh, no,” said she, “here is my own work upon it. My
husband, my husband! God, look down upon me!” Amongst
those who anxiously inspected this relic was the Rev. Mr. Lewis,
a Wesleyan minister. Two of his brothers were aboard the ship—
one as purser. Their arrival at Queenstown had been
telegraphed to their aged mother, who wrote to the rev.
gentleman to meet them at Liverpool. He now, poor fellow,
paces the shore at Molfra Bay to watch for the dead bodies. Five
bodies were washed ashore at Molfra, and seven at
Penmaenmaur yesterday. None of these have as yet been
identified. No bodies have been washed up to-day. Several of
the dead persons have already been interred in Molfra and
Llanallgo churchyards. The wreck remains in precisely the state
as she was on Wednesday last when the coast-guard from
Amlwch were put in charge. At low water a good piece of her
hull is visible. At high water there are only portions of two of the
masts. As the officials along the line of the London and North-
Western Railway are besieged with inquiries as to where Molfra
Bay is, it may be as well to state that the nearest approach to it
for any person not in the island of Anglesey, is from Bangor
railway station. It is fourteen miles from Bangor, over a horrible
road, with most expensive posting. There is no mode of
communicating with London from it but through Bangor, and
there are no public conveyances of any kind. But,
notwithstanding this, great numbers are visiting the scene. On
the whole, the people in the neighbourhood are reported to
have acted very well. Several sums of money found by them
have been given up to the coast-guard. The fragments of the
spars, and even of the mainmast, seem as if they had been
smashed into small pieces by some crushing blade impelled by
steam power. If an army of giants had fallen to to hew up the
ship it could not have presented a more fragmentary
appearance.’

A correspondent of the Manchester Guardian describes the wreck


from the same stand-point. He says:—

‘Immediately after the adjournment of the inquest, on Friday,


orders were given for the interment of the bodies which had
been identified; the remainder were kept throughout the whole
of Saturday, and every hour brought a fresh accession of visitors
bent on the melancholy errand of inquiry after missing friends.
The distortion and disfigurement of the bodies consequent on
drowning, and the absence of clothing, made the examination
necessarily more minute and painful; but in some instances the
features and limbs were mangled from violent dashing against
the rocks, and recognition of friends was almost impossible. Mr.
Bradbury, a survivor, describes one of the young ladies whose
bodies were lying in Penrhos church as the recognized belle of
the vessel, and the charm and admiration of a large circle. Mrs.
Foster, who is among the lost, had gone to Australia to
superintend the sale of some land, and it is conjectured that she
had with her the whole of the proceeds of the sale. Her
companion, Mrs. Woodroff, who has been identified, was the
wife of an innkeeper in Melbourne: her husband is expected to
follow her. Among the company at Bangor was an elderly
gentleman from Gloucestershire, named Wright, who had heard
of the wreck at Liverpool, where he had come in expectation of
meeting his son, Mr. Iles Wright, of Evesham, who was the
surgeon of the ship, and who had written from Queenstown
anticipatory of his arrival.
‘At low water the remaining portion of the hull of the vessel is
quite discernible, and when the neap tides prevail it is expected
that much of the treasure and many more bodies will be
recovered. The fact that so few, proportionately to the number
lost, have been recovered has occasioned much wonder, and is
variously accounted for. The partition of the vessel is supposed
by some to have enclosed the bodies as in a box. The débris of
the wreck lies scattered about the shore, the woodwork being
literally nothing but chips. The exact position of the wreck is
about a mile and a half from the Llanallgo church, where most
of the bodies are lying. The Anglesea militia, the coast-guard,
and a body of police are placed there for the protection of the
property washed on shore, and a temporary shed is constructed
on the shore. The nearest dwellings to the wreck are at Molfra
village, which is more than half a mile from the spot. Captain
Fell and a staff from Lloyd’s are located there. At the inquest,
which is adjourned to Wednesday, a strict examination is
expected to take place into the statement made of the captain
being intoxicated at the time of the fearful disaster. The
statement is broadly made by some of the survivors; but the
owners of the vessel and some nautical men say they can
triumphantly vindicate the memory of the deceased.
‘Among the Lancashire people lost in the vessel whose friends
came to seek for them on hearing of the wreck, were Mr. Casper
Lewin, nephew of Mr. Adam Casper, of Market Street,
Manchester; Miss Wrigley, Byron Street, Manchester; Mr. and
Mrs. Kirkbride, Liverpool; and Mrs. Robinson, of Southport, wife
of the editor of one of the Melbourne newspapers.’

In a letter dated ‘Molfra, Wednesday afternoon,’ another writer says:


‘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 tone of one part of that communication leads naturally to the


following stinging words from a Liverpool journal:—

‘Loud are the complaints here at the manner in which those


saved from the wreck were treated after their arrival here. It is
said, with great indignation, that when Captain Martin (the
representative of Messrs. Gibb and Brights) arrived here, with
the rescued passengers, in the steam-tug which had been
despatched to the scene of the wreck, he left them standing
upon the landing-stage; and had they not been received at the
Sailors’ Home, they would have had to wander all night about
the streets.’
This, of a verity, is caring more for gold than human bodies. One
would have thought the best accommodation the best hotel in
Liverpool could afford would have been prepared by the owners of
the wrecked vessel in anticipation of the arrival of the poor creatures
whose all, save life, had been buried beneath the waves.
In penning my narrative up to this point, it is impossible but that the
reader should have felt a large amount of interest in the captain and
officers of the vessel. Whatever mistake of those in command may
have brought the ship so near the coast, the heart of every one
must swell as he reads how heroically the storm was coped with.
‘First killed,’ or ‘last seen on the ship,’ are phrases that, like the
noblest epitaphs, are associated with the captain and his officers.
They succumbed, after glorious battling, to the fate of the sailor; but
to show how ill the world could afford to lose such men let me
endeavour, in a few concluding lines, to portray them to the reader.
Brave and rugged as a lion was the captain. His defiant front, his
curt, honest conversation, his implacable will, which, like a wave,
bore down all before it; his natural humour and intense love of
jollity; his large solicitude for his passengers and crew; his all but
feminine love for his ship, and his fervent belief that no other craft
was fit to touch the waters with her,—all these points grow upon me
as I write, and cause me to blur the paper as I lash them to the
name of Thomas Taylor. I do not believe that man was drunk on the
evening of the calamity. This, however, I know, that to those who
were not in constant communication with him, Captain Taylor always
appeared drunk. He had a ruddy face, a quick, abrupt manner, and a
husky utterance which, to the superficial observer, naturally
proclaimed him intoxicated. This concludes on that head: I never
saw Captain Taylor the worse for liquor during our passage home.
On the other hand, I heard him pronounced drunk by second and
third class passengers nightly.
Mr. Stevens, the first officer, was a fine young fellow of some thirty
summers. He was a most agreeable companion, delighted in song or
dance, and if he got a quiet moment with a friend, would talk by the
hour of the young wife and little-ones he had left at home. He made
every one his friend—was a friend to every one.
Mr. Cowie, the second officer (he was third when I came home) was
like a character out of Marryat. He was about three or four and
twenty years of age, was as bold and bluff as the captain; and was
never so delighted as when he was singing ‘Hearts of Oak’ in the
cock-pit.
Mr. Rogers, the chief engineer, was a man of rough exterior, but of
simple, child-like manners. His whole time during my sojourn on the
ship was spent in looking after the engines, and entering into
amusing discussions with the purser on the right pronunciation of
words. Poor fellow!
The purser (Mr. Lewis) was one of the best men that ever walked
the earth. He did justice to passengers and owners, and at the time
when we ran short of food, I knew him, with all the ship’s stores at
his command, to abstain from dinner, that the children of the
intermediate and steerage passengers might in turn receive his
share of the slender stock of dainties left to us on board. He has
gone where stewards cease from troubling!
But why continue these memorials of the dead? We call on the
names of the good and brave men in vain. Saddest of all sad stories
is that which I have attempted to tell. The cheek of the boldest
grows pale as he reads it, and my pen falls from my fingers as the
old familiar faces rise before me.
THE PRESS ON THE CATASTROPHE.
The Times, after some preliminary observations on the gale of
Wednesday, contents itself with a general record of the calamity:—

‘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.’

The Morning Herald, after chronicling the disaster, concludes with


this valuable paragraph:—

‘This greatest and most terrible of the results of the late


hurricane—for it cannot be otherwise described—will argue
strongly either on behalf of those who demand ports of
departure less channel-bound than Liverpool, or for those who
urge the great necessity for a national system of providing life-
boats which shall give, even in such wild bays as this where the
“Royal Charter” went to pieces, a chance to some of the
passengers of ill-fated ships that may be driven into them in
such a storm as that of Tuesday night or Wednesday morning.
Unfortunately the outcry on these subjects rises only while the
mind of the public is resting on such a disaster as that which
has just befallen the “Royal Charter,” or at a time when the
whole country is deploring such a series of wrecks as those
which have strewn our coasts within the last three days. The
life-boat question should certainly not be left to private
benevolence, or to the efforts of companies. Governments have
gone too far in their neglect of such subjects or their refusal to
interfere, and we are certain that there is no other mode of
using the public money which would meet with more hearty
popular assent than that which would devote it to the provision
of life-boats and harbours of refuge.’

The colony may study these words with equal advantage to


ourselves.
The Daily News is none the less able on the subject, because for
once disposed to be smart. Does “Singleton Fontenoy” speak in the
following?—

‘There is a true savour of sea-salt in the grim irony of that


couplet in one of Dibdin’s sea-songs, where Jack is contrasting
the freedom and security of life aboard ship with the continual
jeopardy to which landsmen who walk about streets and dwell
in houses are exposed:—

“While you and I, Bill, on the deck


Are comfortably lying,
My eyes! what tiles and chimbly pots
Around their heads are flying!”

‘The recklessness of temperament which sends a lad to sea, and


which, hardened and confirmed by conflict with the elements,
laughs at real danger, and yet is apt to shrink with a sort of
dismayed disgust from the vulgar inconveniences of artificial
existence, is happily and humorously expressed. The dweller in
cities, on the other hand, with all his habitual scepticism and
indifference, who peeps at the moon as at a raree show, and
takes a return ticket to go and gape at an eclipse from some
distant hill in the country—your acute, hard-headed, practical
man on Change, in the Law-court, in the Club, stares and
marvels like a mere baby when he is brought face to face with
the terror and mystery of Nature in any of her sublimer moods.
A fashionable public at Brighton running out to see the effects
of a gale of wind upon real “water” is surely as sorry and
ludicrous a combination as the genius of mockery can devise for
the laughter of the stars. Accidents and offences, fires and
murders, burglaries and poisonings, are as dull and stale as
taxation, or as births, deaths, and marriages; they are the
“useful and the beautiful” of well-regulated society; and who but
a dry statistical philanthropist reads the wreck-list, or ponders
the significance of the annual catalogue of casualties among
merchantmen and coasters? It is only when the great
meteorological staple of English conversation derives a certain
freshness and novelty from a sudden attack of winter upon the
rear of autumn, or when a hurricane has torn up a tree in the
park and blown an old woman into the river or a child into the
canal, that our inland world begins to feel that the universe is
not absolutely done to order yet.
‘Last Tuesday night, when town and country were well abed,
and let us hope not without thankfulness of heart, nor without
having taken thought of “all those who travel by land or sea;”—
when even the rancid haunts of vice in London were emptying,
and the homeless were slinking off to snatch forgetfulness
somewhere out of reach of wind and rain:—in the dead hour of
a desolate night, desolate enough among street lamps flickering
in a clammy fog, more desolate still when a sickly moon peered
dimly through a drift of ragged cloud, and the wind howled and
moaned with a roar of rage and anguish—in that desolate night
and that dead hour one of those terrible calamities which are
remembered for centuries was hurrying near five hundred of our
fellow-creatures to sudden death at sea, after a safe and
prosperous voyage of twelve thousand miles, within six hours of
port, and within stonethrow of the long-wished-for land.
Heartrending and disastrous is the shipping intelligence of this
week all round our coasts, but the wreck of the “Royal Charter”
will be a melancholy fireside tale among our children’s children.
If, indeed, what is called “progress” be truly defined as an
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

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.

Let us accompany you on the journey of exploring knowledge and


personal growth!

textbookfull.com

You might also like