SlideShare a Scribd company logo
The Rust Programming Language 2nd Edition Second
Converted Steve Klabnik Carol Nichols download
https://ebookbell.com/product/the-rust-programming-language-2nd-
edition-second-converted-steve-klabnik-carol-nichols-49465120
Explore and download more ebooks at ebookbell.com
Here are some recommended products that we believe you will be
interested in. You can click the link to download.
The Rust Programming Language Covers Rust 2018 Illustrated Steve
Klabnik
https://ebookbell.com/product/the-rust-programming-language-covers-
rust-2018-illustrated-steve-klabnik-50194554
The Rust Programming Language Steve Klabnik Carol Nichols
https://ebookbell.com/product/the-rust-programming-language-steve-
klabnik-carol-nichols-36194546
The Rust Programming Language Covers Rust 2018 Steve Klabnik Carol
Nichols
https://ebookbell.com/product/the-rust-programming-language-covers-
rust-2018-steve-klabnik-carol-nichols-49850560
The Rust Programming Language Second Edition 2 Converted Steve Klabnik
https://ebookbell.com/product/the-rust-programming-language-second-
edition-2-converted-steve-klabnik-48000090
The Rust Programming Language 1st Edition The Rust Project Developpers
https://ebookbell.com/product/the-rust-programming-language-1st-
edition-the-rust-project-developpers-23358024
The Rust Programming Language Steve Klabnik Carol Nichols
https://ebookbell.com/product/the-rust-programming-language-steve-
klabnik-carol-nichols-27553790
The Rust Programming Language Steve Klabnik Steve Carol Nichols
https://ebookbell.com/product/the-rust-programming-language-steve-
klabnik-steve-carol-nichols-36194548
The Rust Programming Language Covers Rust 2018 Carol Nichols
https://ebookbell.com/product/the-rust-programming-language-covers-
rust-2018-carol-nichols-37721398
The Rust Programming Language Steve Klabnik Carol Nichols
https://ebookbell.com/product/the-rust-programming-language-steve-
klabnik-carol-nichols-42174614
The Rust Programming Language 2nd Edition Second Converted Steve Klabnik Carol Nichols
The Rust Programming Language 2nd Edition Second Converted Steve Klabnik Carol Nichols
CONTENTS IN DETAIL
TITLE PAGE
COPYRIGHT
ABOUT THE AUTHORS
FOREWORD
PREFACE
ACKNOWLEDGMENTS
INTRODUCTION
Who Rust Is For
Teams of Developers
Students
Companies
Open Source Developers
People Who Value Speed and Stability
Who This Book Is For
How to Use This Book
Resources and How to Contribute to This Book
CHAPTER 1: GETTING STARTED
Installation
Installing rustup on Linux or macOS
Installing rustup on Windows
Troubleshooting
Updating and Uninstalling
Local Documentation
Hello, World!
Creating a Project Directory
Writing and Running a Rust Program
Anatomy of a Rust Program
Compiling and Running Are Separate Steps
Hello, Cargo!
Creating a Project with Cargo
Building and Running a Cargo Project
Building for Release
Cargo as Convention
Summary
CHAPTER 2: PROGRAMMING A GUESSING GAME
Setting Up a New Project
Processing a Guess
Storing Values with Variables
Receiving User Input
Handling Potential Failure with Result
Printing Values with println! Placeholders
Testing the First Part
Generating a Secret Number
Using a Crate to Get More Functionality
Generating a Random Number
Comparing the Guess to the Secret Number
Allowing Multiple Guesses with Looping
Quitting After a Correct Guess
Handling Invalid Input
Summary
CHAPTER 3: COMMON PROGRAMMING CONCEPTS
Variables and Mutability
Constants
Shadowing
Data Types
Scalar Types
Compound Types
Functions
Parameters
Statements and Expressions
Functions with Return Values
Comments
Control Flow
if Expressions
Repetition with Loops
Summary
CHAPTER 4: UNDERSTANDING OWNERSHIP
What Is Ownership?
Ownership Rules
Variable Scope
The String Type
Memory and Allocation
Ownership and Functions
Return Values and Scope
References and Borrowing
Mutable References
Dangling References
The Rules of References
The Slice Type
String Slices
Other Slices
Summary
CHAPTER 5: USING STRUCTS TO STRUCTURE RELATED DATA
Defining and Instantiating Structs
Using the Field Init Shorthand
Creating Instances from Other Instances with Struct Update Syntax
Using Tuple Structs Without Named Fields to Create Different Types
Unit-Like Structs Without Any Fields
An Example Program Using Structs
Refactoring with Tuples
Refactoring with Structs: Adding More Meaning
Adding Useful Functionality with Derived Traits
Method Syntax
Defining Methods
Methods with More Parameters
Associated Functions
Multiple impl Blocks
Summary
CHAPTER 6: ENUMS AND PATTERN MATCHING
Defining an Enum
Enum Values
The Option Enum and Its Advantages Over Null Values
The match Control Flow Construct
Patterns That Bind to Values
Matching with Option<T>
Matches Are Exhaustive
Catch-All Patterns and the _ Placeholder
Concise Control Flow with if let
Summary
CHAPTER 7: MANAGING GROWING PROJECTS WITH PACKAG
ES, CRATES, AND MODULES
Packages and Crates
Defining Modules to Control Scope and Privacy
Paths for Referring to an Item in the Module Tree
Exposing Paths with the pub Keyword
Starting Relative Paths with super
Making Structs and Enums Public
Bringing Paths into Scope with the use Keyword
Creating Idiomatic use Paths
Providing New Names with the as Keyword
Re-exporting Names with pub use
Using External Packages
Using Nested Paths to Clean Up Large use Lists
The Glob Operator
Separating Modules into Different Files
Summary
CHAPTER 8: COMMON COLLECTIONS
Storing Lists of Values with Vectors
Creating a New Vector
Updating a Vector
Reading Elements of Vectors
Iterating Over the Values in a Vector
Using an Enum to Store Multiple Types
Dropping a Vector Drops Its Elements
Storing UTF-8 Encoded Text with Strings
What Is a String?
Creating a New String
Updating a String
Indexing into Strings
Slicing Strings
Methods for Iterating Over Strings
Strings Are Not So Simple
Storing Keys with Associated Values in Hash Maps
Creating a New Hash Map
Accessing Values in a Hash Map
Hash Maps and Ownership
Updating a Hash Map
Hashing Functions
Summary
CHAPTER 9: ERROR HANDLING
Unrecoverable Errors with panic!
Recoverable Errors with Result
Matching on Different Errors
Propagating Errors
To panic! or Not to panic!
Examples, Prototype Code, and Tests
Cases in Which You Have More Information Than the Compiler
Guidelines for Error Handling
Creating Custom Types for Validation
Summary
CHAPTER 10: GENERIC TYPES, TRAITS, AND LIFETIMES
Removing Duplication by Extracting a Function
Generic Data Types
In Function Definitions
In Struct Definitions
In Enum Definitions
In Method Definitions
Performance of Code Using Generics
Traits: Defining Shared Behavior
Defining a Trait
Implementing a Trait on a Type
Default Implementations
Traits as Parameters
Returning Types That Implement Traits
Using Trait Bounds to Conditionally Implement Methods
Validating References with Lifetimes
Preventing Dangling References with Lifetimes
The Borrow Checker
Generic Lifetimes in Functions
Lifetime Annotation Syntax
Lifetime Annotations in Function Signatures
Thinking in Terms of Lifetimes
Lifetime Annotations in Struct Definitions
Lifetime Elision
Lifetime Annotations in Method Definitions
The Static Lifetime
Generic Type Parameters, Trait Bounds, and Lifetimes Together
Summary
CHAPTER 11: WRITING AUTOMATED TESTS
How to Write Tests
The Anatomy of a Test Function
Checking Results with the assert! Macro
Testing Equality with the assert_eq! and assert_ne! Macros
Adding Custom Failure Messages
Checking for Panics with should_panic
Using Result<T, E> in Tests
Controlling How Tests Are Run
Running Tests in Parallel or Consecutively
Showing Function Output
Running a Subset of Tests by Name
Ignoring Some Tests Unless Specifically Requested
Test Organization
Unit Tests
Integration Tests
Summary
CHAPTER 12: AN I/O PROJECT: BUILDING A COMMAND LINE P
ROGRAM
Accepting Command Line Arguments
Reading the Argument Values
Saving the Argument Values in Variables
Reading a File
Refactoring to Improve Modularity and Error Handling
Separation of Concerns for Binary Projects
Fixing the Error Handling
Extracting Logic from main
Splitting Code into a Library Crate
Developing the Library’s Functionality with Test-Driven Development
Writing a Failing Test
Writing Code to Pass the Test
Working with Environment Variables
Writing a Failing Test for the Case-Insensitive Search Function
Implementing the search_case_insensitive Function
Writing Error Messages to Standard Error Instead of Standard Outpu
t
Checking Where Errors Are Written
Printing Errors to Standard Error
Summary
CHAPTER 13: FUNCTIONAL LANGUAGE FEATURES: ITERATO
RS AND CLOSURES
Closures: Anonymous Functions That Capture Their Environment
Capturing the Environment with Closures
Closure Type Inference and Annotation
Capturing References or Moving Ownership
Moving Captured Values Out of Closures and the Fn Traits
Processing a Series of Items with Iterators
The Iterator Trait and the next Method
Methods That Consume the Iterator
Methods That Produce Other Iterators
Using Closures That Capture Their Environment
Improving Our I/O Project
Removing a clone Using an Iterator
Making Code Clearer with Iterator Adapters
Choosing Between Loops and Iterators
Comparing Performance: Loops vs. Iterators
Summary
CHAPTER 14: MORE ABOUT CARGO AND CRATES.IO
Customizing Builds with Release Profiles
Publishing a Crate to Crates.io
Making Useful Documentation Comments
Exporting a Convenient Public API with pub use
Setting Up a Crates.io Account
Adding Metadata to a New Crate
Publishing to Crates.io
Publishing a New Version of an Existing Crate
Deprecating Versions from Crates.io with cargo yank
Cargo Workspaces
Creating a Workspace
Creating the Second Package in the Workspace
Installing Binaries with cargo install
Extending Cargo with Custom Commands
Summary
CHAPTER 15: SMART POINTERS
Using Box<T> to Point to Data on the Heap
Using Box<T> to Store Data on the Heap
Enabling Recursive Types with Boxes
Treating Smart Pointers Like Regular References with Deref
Following the Pointer to the Value
Using Box<T> Like a Reference
Defining Our Own Smart Pointer
Implementing the Deref Trait
Implicit Deref Coercions with Functions and Methods
How Deref Coercion Interacts with Mutability
Running Code on Cleanup with the Drop Trait
Rc<T>, the Reference Counted Smart Pointer
Using Rc<T> to Share Data
Cloning an Rc<T> Increases the Reference Count
RefCell<T> and the Interior Mutability Pattern
Enforcing Borrowing Rules at Runtime with RefCell<T>
Interior Mutability: A Mutable Borrow to an Immutable Value
Allowing Multiple Owners of Mutable Data with Rc<T> and RefCell<
T>
Reference Cycles Can Leak Memory
Creating a Reference Cycle
Preventing Reference Cycles Using Weak<T>
Summary
CHAPTER 16: FEARLESS CONCURRENCY
Using Threads to Run Code Simultaneously
Creating a New Thread with spawn
Waiting for All Threads to Finish Using join Handles
Using move Closures with Threads
Using Message Passing to Transfer Data Between Threads
Channels and Ownership Transference
Sending Multiple Values and Seeing the Receiver Waiting
Creating Multiple Producers by Cloning the Transmitter
Shared-State Concurrency
Using Mutexes to Allow Access to Data from One Thread at a Time
Similarities Between RefCell<T>/Rc<T> and Mutex<T>/Arc<T>
Extensible Concurrency with the Send and Sync Traits
Allowing Transference of Ownership Between Threads with Send
Allowing Access from Multiple Threads with Sync
Implementing Send and Sync Manually Is Unsafe
Summary
CHAPTER 17: OBJECT-ORIENTED PROGRAMMING FEATURES
Characteristics of Object-Oriented Languages
Objects Contain Data and Behavior
Encapsulation That Hides Implementation Details
Inheritance as a Type System and as Code Sharing
Using Trait Objects That Allow for Values of Different Types
Defining a Trait for Common Behavior
Implementing the Trait
Trait Objects Perform Dynamic Dispatch
Implementing an Object-Oriented Design Pattern
Defining Post and Creating a New Instance in the Draft State
Storing the Text of the Post Content
Ensuring the Content of a Draft Post Is Empty
Requesting a Review Changes the Post’s State
Adding approve to Change the Behavior of content
Trade-offs of the State Pattern
Summary
CHAPTER 18: PATTERNS AND MATCHING
All the Places Patterns Can Be Used
match Arms
Conditional if let Expressions
while let Conditional Loops
for Loops
let Statements
Function Parameters
Refutability: Whether a Pattern Might Fail to Match
Pattern Syntax
Matching Literals
Matching Named Variables
Multiple Patterns
Matching Ranges of Values with ..=
Destructuring to Break Apart Values
Ignoring Values in a Pattern
Extra Conditionals with Match Guards
@ Bindings
Summary
CHAPTER 19: ADVANCED FEATURES
Unsafe Rust
Unsafe Superpowers
Dereferencing a Raw Pointer
Calling an Unsafe Function or Method
Accessing or Modifying a Mutable Static Variable
Implementing an Unsafe Trait
Accessing Fields of a Union
When to Use Unsafe Code
Advanced Traits
Associated Types
Default Generic Type Parameters and Operator Overloading
Disambiguating Between Methods with the Same Name
Using Supertraits
Using the Newtype Pattern to Implement External Traits
Advanced Types
Using the Newtype Pattern for Type Safety and Abstraction
Creating Type Synonyms with Type Aliases
The Never Type That Never Returns
Dynamically Sized Types and the Sized Trait
Advanced Functions and Closures
Function Pointers
Returning Closures
Macros
The Difference Between Macros and Functions
Declarative Macros with macro_rules! for General Metaprogramming
Procedural Macros for Generating Code from Attributes
How to Write a Custom derive Macro
Attribute-Like Macros
Function-Like Macros
Summary
CHAPTER 20: FINAL PROJECT: BUILDING A MULTITHREADED
WEB SERVER
Building a Single-Threaded Web Server
Listening to the TCP Connection
Reading the Request
A Closer Look at an HTTP Request
Writing a Response
Returning Real HTML
Validating the Request and Selectively Responding
A Touch of Refactoring
Turning Our Single-Threaded Server into a Multithreaded Server
Simulating a Slow Request
Improving Throughput with a Thread Pool
Graceful Shutdown and Cleanup
Implementing the Drop Trait on ThreadPool
Signaling to the Threads to Stop Listening for Jobs
Summary
APPENDIX A: KEYWORDS
Keywords Currently in Use
Keywords Reserved for Future Use
Raw Identifiers
APPENDIX B: OPERATORS AND SYMBOLS
Operators
Non-operator Symbols
APPENDIX C: DERIVABLE TRAITS
Debug for Programmer Output
PartialEq and Eq for Equality Comparisons
PartialOrd and Ord for Ordering Comparisons
Clone and Copy for Duplicating Values
Hash for Mapping a Value to a Value of Fixed Size
Default for Default Values
APPENDIX D: USEFUL DEVELOPMENT TOOLS
Automatic Formatting with rustfmt
Fix Your Code with rustfix
More Lints with Clippy
IDE Integration Using rust-analyzer
APPENDIX E: EDITIONS
INDEX
THE RUST PROGRAMMING
LANGUAGE
2nd Edition
by Steve Klabnik and Carol Nichols, with
contributions from the Rust Community
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.
Printed in the United States of America
First printing
27 26 25 24 23 1 2 3 4 5
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
For information on distribution, bulk sales, corporate sales, or translations, please
contact No Starch Press, Inc. directly at info@nostarch.com or:
No Starch Press, Inc.
245 8th Street, San Francisco, CA 94103
phone: 1.415.863.9900
www.nostarch.com
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
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 contributor, 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
member 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.
FOREWORD
It wasn’t always so clear, but the Rust programming language is
fundamentally 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
providing 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 having 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 mistakes 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 programmer in general. So dive in, get ready to
learn—and welcome to the Rust community!
Nicholas Matsakis and Aaron Turon
PREFACE
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 configure them to use Rust 2021 edition idioms. See
“Installation” on page 1 for instructions on installing or updating Rust,
and see Appendix E for information on editions.
The 2021 edition of the Rust language includes a number of
improvements 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!
ACKNOWLEDGMENTS
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 technical
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
programming world:
Cargo, the included dependency manager and build tool, makes
adding, 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 operating 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, especially those new to
programming.
Companies
Hundreds of companies, large and small, use Rust in production for
a variety of tasks, including command line tools, web services,
DevOps tooling, embedded devices, audio and video analysis and
transcoding, cryptocurrencies, bioinformatics, search engines,
Internet of Things applications, machine learning, and even major
parts of the Firefox web browser.
Open Source Developers
Rust is for people who want to build the Rust programming
language, community, 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 endeavors 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 ergonomics. 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
language, 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 programming 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 programming, 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 your hands dirty right
away, Chapter 2 is the place for that. Chapter 3 covers Rust
features that are similar to those of other programming languages,
and in Chapter 4 you’ll learn about Rust’s ownership system. If
you’re a particularly meticulous learner who prefers to learn every
detail before moving on to the next, you might want to skip Chapter 2
and go straight to Chapter 3, returning to Chapter 2 when you’d like
to work on a project applying the details you’ve learned.
Chapter 5 discusses structs and methods, and Chapter 6 covers
enums, match expressions, and the if let control flow construct.
You’ll use structs and enums to make custom types in Rust.
In Chapter 7, you’ll learn about Rust’s module system and about
privacy rules for organizing your code and its public application
programming interface (API). Chapter 8 discusses some common
collection data structures that the standard library provides, such as
vectors, strings, and hash maps. Chapter 9 explores Rust’s error-
handling philosophy and techniques.
Chapter 10 digs into generics, traits, and lifetimes, which give you
the power to define code that applies to multiple types. Chapter 11 is
all about testing, which even with Rust’s safety guarantees is
necessary to ensure your program’s logic is correct. In Chapter 12,
we’ll build our own implementation of a subset of functionality from
the grep command line tool that searches for text within files. For
this, we’ll use many of the concepts we discussed in the previous
chapters.
Chapter 13 explores closures and iterators: features of Rust that
come from functional programming languages. In Chapter 14, we’ll
examine Cargo in more depth and talk about best practices for
sharing your libraries with others. Chapter 15 discusses smart
pointers that the standard library provides and the traits that enable
their functionality.
In Chapter 16, we’ll walk through different models of concurrent
programming and talk about how Rust helps you program in multiple
threads fearlessly. Chapter 17 looks at how Rust idioms compare to
object-oriented programming principles you might be familiar with.
Chapter 18 is a reference on patterns and pattern matching,
which are powerful ways of expressing ideas throughout Rust
programs. Chapter 19 contains a smorgasbord of advanced topics
of interest, including unsafe Rust, macros, and more about lifetimes,
traits, types, functions, and closures.
In Chapter 20, we’ll complete a project in which we’ll implement a
low-level multithreaded web server!
Finally, some appendixes contain useful information about the
language in a more reference-like format. Appendix A covers Rust’s
keywords, Appendix B covers Rust’s operators and symbols,
Appendix C covers derivable traits provided by the standard library,
Appendix D covers some useful development tools, and Appendix
E explains Rust editions.
There is no wrong way to read this book: if you want to skip
ahead, go for it! You might have to jump back to earlier chapters if
you experience any confusion. But do whatever works for you.
An important part of the process of learning Rust is learning how
to read the error messages the compiler displays: these will guide
you toward working code. As such, we’ll provide many examples that
don’t compile along with the error message the compiler will show
you in each situation. Know that if you enter and run a random
example, it may not compile! Make sure you read the surrounding
text to see whether the example you’re trying to run is meant to error.
In most situations, we’ll lead you to the correct version of any code
that doesn’t compile.
Resources and How to Contribute to This Book
This book is open source. If you find an error, please don’t hesitate
to file an issue or send a pull request on GitHub at https://github.co
m/rust-lang/book. Please see CONTRIBUTING.md at https://github.c
om/rust-lang/book/blob/main/CONTRIBUTING.md for more details.
The source code for the examples in this book, errata, and other
information are available at https://nostarch.com/rust-programming-l
anguage-2nd-edition.
1
GETTING STARTED
Let’s start your Rust journey! There’s a
lot to learn, but every journey starts
somewhere. In this chapter, we’ll
discuss:
Installing Rust on Linux, macOS, and Windows
Writing a program that prints Hello, world!
Using cargo, Rust’s package manager and build system
Installation
The first step is to install Rust. We’ll download Rust through rustup,
a command line tool for managing Rust versions and associated
tools. You’ll need an internet connection for the download.
NOTE
If you prefer not to use rustup for some reason, please see
the Other Rust Installation Methods page at https://forge.rust-l
ang.org/infra/other-installation-methods.xhtml for more
options.
The following steps install the latest stable version of the Rust
compiler. Rust’s stability guarantees ensure that all the examples in
the book that compile will continue to compile with newer Rust
versions. The output might differ slightly between versions because
Rust often improves error messages and warnings. In other words,
any newer, stable version of Rust you install using these steps
should work as expected with the content of this book.
COMMAND LINE NOTATION
In this chapter and throughout the book, we’ll show some commands used in
the terminal. Lines that you should enter in a terminal all start with $. You don’t
need to type the $ character; it’s the command line prompt shown to indicate
the start of each command. Lines that don’t start with $ typically show the
output of the previous command. Additionally, PowerShell-specific examples
will use > rather than $.
Installing rustup on Linux or macOS
If you’re using Linux or macOS, open a terminal and enter the
following command:
$ curl --proto '=https' --tlsv1.3 https://sh.rustup.rs -sSf |
sh
The command downloads a script and starts the installation of the
rustup tool, which installs the latest stable version of Rust. You might
be prompted for your password. If the install is successful, the
following line will appear:
Rust is installed now. Great!
You will also need a linker, which is a program that Rust uses to
join its compiled outputs into one file. It is likely you already have
one. If you get linker errors, you should install a C compiler, which
will typically include a linker. A C compiler is also useful because
some common Rust packages depend on C code and will need a C
compiler.
On macOS, you can get a C compiler by running:
$ xcode-select --install
Linux users should generally install GCC or Clang, according to
their distribution’s documentation. For example, if you use Ubuntu,
you can install the build-essential package.
Installing rustup on Windows
On Windows, go to https://www.rust-lang.org/tools/install and follow
the instructions for installing Rust. At some point in the installation,
you’ll receive a message explaining that you’ll also need the MSVC
build tools for Visual Studio 2013 or later.
To acquire the build tools, you’ll need to install Visual Studio 2022
from https://visualstudio.microsoft.com/downloads. When asked
which workloads to install, include:
“Desktop Development with C++”
The Windows 10 or 11 SDK
The English language pack component, along with any other
language pack of your choosing
The rest of this book uses commands that work in both cmd.exe
and PowerShell. If there are specific differences, we’ll explain which
to use.
Troubleshooting
To check whether you have Rust installed correctly, open a shell and
enter this line:
$ rustc --version
You should see the version number, commit hash, and commit
date for the latest stable version that has been released, in the
following format:
rustc x.y.z (abcabcabc yyyy-mm-dd)
If you see this information, you have installed Rust successfully! If
you don’t see this information, check that Rust is in your %PATH%
system variable as follows.
In Windows CMD, use:
> echo %PATH%
In PowerShell, use:
> echo $env:Path
In Linux and macOS, use:
$ echo $PATH
If that’s all correct and Rust still isn’t working, there are a number
of places you can get help. Find out how to get in touch with other
Rustaceans (a silly nickname we call ourselves) on the community
page at https://www.rust-lang.org/community.
Updating and Uninstalling
Once Rust is installed via rustup, updating to a newly released
version is easy. From your shell, run the following update script:
$ rustup update
To uninstall Rust and rustup, run the following uninstall script from
your shell:
$ rustup self uninstall
Local Documentation
The installation of Rust also includes a local copy of the
documentation so that you can read it offline. Run rustup doc to
open the local documentation in your browser.
Any time a type or function is provided by the standard library and
you’re not sure what it does or how to use it, use the application
programming interface (API) documentation to find out!
Hello, World!
Now that you’ve installed Rust, it’s time to write your first Rust
program. It’s traditional when learning a new language to write a little
program that prints the text Hello, world! to the screen, so we’ll do
the same here!
NOTE
This book assumes basic familiarity with the command line.
Rust makes no specific demands about your editing or tooling
or where your code lives, so if you prefer to use an integrated
development environment (IDE) instead of the command line,
feel free to use your favorite IDE. Many IDEs now have some
degree of Rust support; check the IDE’s documentation for
details. The Rust team has been focusing on enabling great
IDE support via rust-analyzer. See Appendix D for more
details.
Creating a Project Directory
You’ll start by making a directory to store your Rust code. It doesn’t
matter to Rust where your code lives, but for the exercises and
projects in this book, we suggest making a projects directory in your
home directory and keeping all your projects there.
Open a terminal and enter the following commands to make a
projects directory and a directory for the “Hello, world!” project within
the projects directory.
For Linux, macOS, and PowerShell on Windows, enter this:
$ mkdir ~/projects
$ cd ~/projects
$ mkdir hello_world
$ cd hello_world
For Windows CMD, enter this:
> mkdir "%USERPROFILE%projects"
> cd /d "%USERPROFILE%projects"
> mkdir hello_world
> cd hello_world
Writing and Running a Rust Program
Next, make a new source file and call it main.rs. Rust files always
end with the .rs extension. If you’re using more than one word in
your filename, the convention is to use an underscore to separate
them. For example, use hello_world.rs rather than helloworld.rs.
Now open the main.rs file you just created and enter the code in Li
sting 1-1.
main.rs
fn main() {
println!("Hello, world!");
}
Listing 1-1: A program that prints Hello, world!
Save the file and go back to your terminal window in the
~/projects/hello_world directory. On Linux or macOS, enter the
following commands to compile and run the file:
$ rustc main.rs
$ ./main
Hello, world!
On Windows, enter the command .main.exe instead of ./main:
> rustc main.rs
> .main.exe
Hello, world!
Regardless of your operating system, the string Hello, world!
should print to the terminal. If you don’t see this output, refer back to
“Troubleshooting” on page 3 for ways to get help.
If Hello, world! did print, congratulations! You’ve officially written
a Rust program. That makes you a Rust programmer—welcome!
Anatomy of a Rust Program
Let’s review this “Hello, world!” program in detail. Here’s the first
piece of the puzzle:
fn main() {
}
These lines define a function named main. The main function is
special: it is always the first code that runs in every executable Rust
program. Here, the first line declares a function named main that has
no parameters and returns nothing. If there were parameters, they
would go inside the parentheses ().
The function body is wrapped in {}. Rust requires curly brackets
around all function bodies. It’s good style to place the opening curly
bracket on the same line as the function declaration, adding one
space in between.
NOTE
If you want to stick to a standard style across Rust projects,
you can use an automatic formatter tool called rustfmt to
format your code in a particular style (more on rustfmt in
Appendix D). The Rust team has included this tool with the
standard Rust distribution, as rustc is, so it should already be
installed on your computer!
The body of the main function holds the following code:
println!("Hello, world!");
This line does all the work in this little program: it prints text to the
screen. There are four important details to notice here.
First, Rust style is to indent with four spaces, not a tab.
Second, println! calls a Rust macro. If it had called a function
instead, it would be entered as println (without the !). We’ll discuss
Rust macros in more detail in Chapter 19. For now, you just need to
know that using a ! means that you’re calling a macro instead of a
normal function and that macros don’t always follow the same rules
as functions.
Third, you see the "Hello, world!" string. We pass this string as
an argument to println!, and the string is printed to the screen.
Fourth, we end the line with a semicolon (;), which indicates that
this expression is over and the next one is ready to begin. Most lines
of Rust code end with a semicolon.
Compiling and Running Are Separate Steps
You’ve just run a newly created program, so let’s examine each step
in the process.
Before running a Rust program, you must compile it using the Rust
compiler by entering the rustc command and passing it the name of
your source file, like this:
$ rustc main.rs
If you have a C or C++ background, you’ll notice that this is similar
to gcc or clang. After compiling successfully, Rust outputs a binary
executable.
On Linux, macOS, and PowerShell on Windows, you can see the
executable by entering the ls command in your shell:
$ ls
main main.rs
On Linux and macOS, you’ll see two files. With PowerShell on
Windows, you’ll see the same three files that you would see using
CMD. With CMD on Windows, you would enter the following:
> dir /B %= the /B option says to only show the file names =%
main.exe
main.pdb
main.rs
This shows the source code file with the .rs extension, the
executable file (main.exe on Windows, but main on all other
platforms), and, when using Windows, a file containing debugging
information with the .pdb extension. From here, you run the main or
main.exe file, like this:
$ ./main # or .main.exe on Windows
If your main.rs is your “Hello, world!” program, this line prints
Hello, world! to your terminal.
If you’re more familiar with a dynamic language, such as Ruby,
Python, or JavaScript, you might not be used to compiling and
running a program as separate steps. Rust is an ahead-of-time
compiled language, meaning you can compile a program and give
the executable to someone else, and they can run it even without
having Rust installed. If you give someone a .rb, .py, or .js file, they
need to have a Ruby, Python, or JavaScript implementation installed
(respectively). But in those languages, you only need one command
to compile and run your program. Everything is a trade-off in
language design.
Just compiling with rustc is fine for simple programs, but as your
project grows, you’ll want to manage all the options and make it easy
to share your code. Next, we’ll introduce you to the Cargo tool, which
will help you write real-world Rust programs.
Hello, Cargo!
Cargo is Rust’s build system and package manager. Most
Rustaceans use this tool to manage their Rust projects because
Cargo handles a lot of tasks for you, such as building your code,
downloading the libraries your code depends on, and building those
libraries. (We call the libraries that your code needs dependencies.)
The simplest Rust programs, like the one we’ve written so far,
don’t have any dependencies. If we had built the “Hello, world!”
project with Cargo, it would only use the part of Cargo that handles
building your code. As you write more complex Rust programs, you’ll
add dependencies, and if you start a project using Cargo, adding
dependencies will be much easier to do.
Because the vast majority of Rust projects use Cargo, the rest of
this book assumes that you’re using Cargo too. Cargo comes
installed with Rust if you used the official installers discussed in
“Installation” on page 1. If you installed Rust through some other
means, check whether Cargo is installed by entering the following in
your terminal:
$ cargo --version
If you see a version number, you have it! If you see an error, such
as command not found, look at the documentation for your method of
installation to determine how to install Cargo separately.
Creating a Project with Cargo
Let’s create a new project using Cargo and look at how it differs from
our original “Hello, world!” project. Navigate back to your projects
directory (or wherever you decided to store your code). Then, on any
operating system, run the following:
$ cargo new hello_cargo
$ cd hello_cargo
The first command creates a new directory and project called
hello_cargo. We’ve named our project hello_cargo, and Cargo
creates its files in a directory of the same name.
Go into the hello_cargo directory and list the files. You’ll see that
Cargo has generated two files and one directory for us: a Cargo.toml
file and a src directory with a main.rs file inside.
It has also initialized a new Git repository along with a .gitignore
file. Git files won’t be generated if you run cargo new within an
existing Git repository; you can override this behavior by using cargo
new --vcs=git.
NOTE
Git is a common version control system. You can change
cargo new to use a different version control system or no
version control system by using the --vcs flag. Run cargo new
--help to see the available options.
Open Cargo.toml in your text editor of choice. It should look similar
to the code in Listing 1-2.
Cargo.toml
[package]
name = "hello_cargo"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lan
g.org/cargo/reference/manifest.xhtml
[dependencies]
Listing 1-2: Contents of Cargo.toml generated by cargo new
This file is in the TOML (Tom’s Obvious, Minimal Language)
format, which is Cargo’s configuration format.
The first line, [package], is a section heading that indicates that the
following statements are configuring a package. As we add more
information to this file, we’ll add other sections.
The next three lines set the configuration information Cargo needs
to compile your program: the name, the version, and the edition of
Rust to use. We’ll talk about the edition key in Appendix E.
The last line, [dependencies], is the start of a section for you to list
any of your project’s dependencies. In Rust, packages of code are
referred to as crates. We won’t need any other crates for this project,
but we will in the first project in Chapter 2, so we’ll use this
dependencies section then.
Now open src/main.rs and take a look:
src/main.rs
fn main() {
println!("Hello, world!");
}
Cargo has generated a “Hello, world!” program for you, just like
the one we wrote in Listing 1-1! So far, the differences between our
project and the project Cargo generated are that Cargo placed the
code in the src directory and we have a Cargo.toml configuration file
in the top directory.
Cargo expects your source files to live inside the src directory. The
top-level project directory is just for README files, license
information, configuration files, and anything else not related to your
code. Using Cargo helps you organize your projects. There’s a place
for everything, and everything is in its place.
If you started a project that doesn’t use Cargo, as we did with the
“Hello, world!” project, you can convert it to a project that does use
Cargo. Move the project code into the src directory and create an
appropriate Cargo.toml file.
Building and Running a Cargo Project
Now let’s look at what’s different when we build and run the “Hello,
world!” program with Cargo! From your hello_cargo directory, build
your project by entering the following command:
$ cargo build
Compiling hello_cargo v0.1.0 (file:///projects/hello_carg
o)
Finished dev [unoptimized + debuginfo] target(s) in 2.85
secs
This command creates an executable file in
target/debug/hello_cargo (or targetdebughello_cargo.exe on
Windows) rather than in your current directory. Because the default
build is a debug build, Cargo puts the binary in a directory named
debug. You can run the executable with this command:
$ ./target/debug/hello_cargo # or .targetdebughello_cargo.
exe on Windows
Hello, world!
If all goes well, Hello, world! should print to the terminal. Running
cargo build for the first time also causes Cargo to create a new file
at the top level: Cargo.lock. This file keeps track of the exact
versions of dependencies in your project. This project doesn’t have
dependencies, so the file is a bit sparse. You won’t ever need to
change this file manually; Cargo manages its contents for you.
We just built a project with cargo build and ran it with
./target/debug/hello_cargo, but we can also use cargo run to
compile the code and then run the resultant executable all in one
command:
$ cargo run
Finished dev [unoptimized + debuginfo] target(s) in 0.0 s
ecs
Running `target/debug/hello_cargo`
Hello, world!
Using cargo run is more convenient than having to remember to
run cargo build and then use the whole path to the binary, so most
developers use cargo run.
Notice that this time we didn’t see output indicating that Cargo was
compiling hello_cargo. Cargo figured out that the files hadn’t
changed, so it didn’t rebuild but just ran the binary. If you had
modified your source code, Cargo would have rebuilt the project
before running it, and you would have seen this output:
$ cargo run
Compiling hello_cargo v0.1.0 (file:///projects/hello_carg
o)
Finished dev [unoptimized + debuginfo] target(s) in 0.33
secs
Running `target/debug/hello_cargo`
Hello, world!
Cargo also provides a command called cargo check. This
command quickly checks your code to make sure it compiles but
doesn’t produce an executable:
$ cargo check
Checking hello_cargo v0.1.0 (file:///projects/hello_cargo)
Finished dev [unoptimized + debuginfo] target(s) in 0.32
secs
Why would you not want an executable? Often, cargo check is
much faster than cargo build because it skips the step of producing
an executable. If you’re continually checking your work while writing
the code, using cargo check will speed up the process of letting you
know if your project is still compiling! As such, many Rustaceans run
cargo check periodically as they write their program to make sure it
compiles. Then they run cargo build when they’re ready to use the
executable.
Let’s recap what we’ve learned so far about Cargo:
We can create a project using cargo new.
We can build a project using cargo build.
We can build and run a project in one step using cargo run.
We can build a project without producing a binary to check for errors
using cargo check.
Instead of saving the result of the build in the same directory as our
code, Cargo stores it in the target/debug directory.
An additional advantage of using Cargo is that the commands are
the same no matter which operating system you’re working on. So,
at this point, we’ll no longer provide specific instructions for Linux
and macOS versus Windows.
Building for Release
When your project is finally ready for release, you can use cargo
build --release to compile it with optimizations. This command will
create an executable in target/release instead of target/debug. The
optimizations make your Rust code run faster, but turning them on
lengthens the time it takes for your program to compile. This is why
there are two different profiles: one for development, when you want
to rebuild quickly and often, and another for building the final
program you’ll give to a user that won’t be rebuilt repeatedly and that
will run as fast as possible. If you’re benchmarking your code’s
running time, be sure to run cargo build --release and benchmark
with the executable in target/release.
Cargo as Convention
With simple projects, Cargo doesn’t provide a lot of value over just
using rustc, but it will prove its worth as your programs become
more intricate. Once programs grow to multiple files or need a
dependency, it’s much easier to let Cargo coordinate the build.
Even though the hello_cargo project is simple, it now uses much
of the real tooling you’ll use in the rest of your Rust career. In fact, to
work on any existing projects, you can use the following commands
to check out the code using Git, change to that project’s directory,
and build:
$ git clone example.org/someproject
$ cd someproject
$ cargo build
For more information about Cargo, check out its documentation at
https://doc.rust-lang.org/cargo.
Summary
You’re already off to a great start on your Rust journey! In this
chapter, you’ve learned how to:
Install the latest stable version of Rust using rustup
Update to a newer Rust version
Open locally installed documentation
Write and run a “Hello, world!” program using rustc directly
Create and run a new project using the conventions of Cargo
This is a great time to build a more substantial program to get
used to reading and writing Rust code. So, in Chapter 2, we’ll build a
guessing game program. If you would rather start by learning how
common programming concepts work in Rust, see Chapter 3 and
then return to Chapter 2.
2
PROGRAMMING A GUESSING GAME
Let’s jump into Rust by working through
a hands-on project together! This
chapter introduces you to a few
common Rust concepts by showing you
how to use them in a real program.
You’ll learn about let, match, methods,
associated functions, external crates, and more! In
the following chapters, we’ll explore these ideas in
more detail. In this chapter, you’ll just practice the
fundamentals.
We’ll implement a classic beginner programming problem: a
guessing game. Here’s how it works: the program will generate a
random integer between 1 and 100. It will then prompt the player to
enter a guess. After a guess is entered, the program will indicate
whether the guess is too low or too high. If the guess is correct, the
game will print a congratulatory message and exit.
Setting Up a New Project
To set up a new project, go to the projects directory that you created
in Chapter 1 and make a new project using Cargo, like so:
$ cargo new guessing_game
$ cd guessing_game
The first command, cargo new, takes the name of the project
(guessing_game) as the first argument. The second command
changes to the new project’s directory.
Look at the generated Cargo.toml file:
Cargo.toml
[package]
name = "guessing_game"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lan
g.org/cargo
/reference/manifest.xhtml
[dependencies]
As you saw in Chapter 1, cargo new generates a “Hello, world!”
program for you. Check out the src/main.rs file:
src/main.rs
fn main() {
println!("Hello, world!");
}
Now let’s compile this “Hello, world!” program and run it in the
same step using the cargo run command:
$ cargo run
Compiling guessing_game v0.1.0 (file:///projects/guessing_
game)
Finished dev [unoptimized + debuginfo] target(s) in 1.50s
Running `target/debug/guessing_game`
Hello, world!
The run command comes in handy when you need to rapidly
iterate on a project, as we’ll do in this game, quickly testing each
iteration before moving on to the next one.
Reopen the src/main.rs file. You’ll be writing all the code in this file.
Processing a Guess
The first part of the guessing game program will ask for user input,
process that input, and check that the input is in the expected form.
To start, we’ll allow the player to input a guess. Enter the code in Listi
ng 2-1 into src/main.rs.
src/main.rs
use std::io;
fn main() {
println!("Guess the number!");
println!("Please input your guess.");
let mut guess = String::new();
io::stdin()
.read_line(&mut guess)
.expect("Failed to read line");
println!("You guessed: {guess}");
}
Listing 2-1: Code that gets a guess from the user and prints it
This code contains a lot of information, so let’s go over it line by
line. To obtain user input and then print the result as output, we need
to bring the io input/output library into scope. The io library comes
from the standard library, known as std:
use std::io;
By default, Rust has a set of items defined in the standard library
that it brings into the scope of every program. This set is called the
prelude, and you can see everything in it at https://doc.rust-lang.org/
std/prelude/index.xhtml.
Random documents with unrelated
content Scribd suggests to you:
Stores of corn sold
under price to the
country labourers.
The same plan was also adopted in the country. It
was recommended by the Council, but it is not
one of the fixed regulations enforced by them. In
one case however we find that a small sum of money had been
collected for a magazine of corn in Suffolk, and that now the Council
ordered it to be used to supply the poor of Halesworth[441].
In many other cases corn was provided by the inhabitants
themselves often by voluntary agreement made under the
persuasion of the justices. In 1623 this method of helping the poor
was usual in Hertfordshire. In March the Sheriff sends to the Council
reports from the justices of the greater part of the country. He states
that the justices and gentlemen have "by there good and charitable
exsamples and perswasiones" provided a quantity of corn at nearly
half the market price in "euery parish where neede requireth." There
was enough to last until next harvest and they hope "noe complainte
of the pore shall hereafter add any disturbance unto his Mati's
most
graciouse pittifull, and charitable minde[442]."
In districts of Devonshire and Suffolk[443] also like plans were tried
in 1623, while in 1631 similar methods of relief seem to have been
universal in the counties of Essex and Norfolk, and to have been
adopted in some districts in almost every eastern county.
Thus in December 1630 in four of the hundreds of Essex
arrangements were made for supplying the people with corn at
home. The chief inhabitants "of theire owne accords" laid in a store
for the poor allowing 7d., 18d. or 2s. the bushel and giving an
equivalent amount in money to those that did not bake their own
bread[444]. Next month we hear that this plan had been adopted in
most of the shire; every parish had its store and the poor were
served at 18d. and 2s. a bushel under the usual price. Sometimes
when grain was scarce, bread and money were given instead. Our
informant states that this provision of corn for the poor at cheap
rates had had a considerable effect in lowering the price of
grain[445]. From every hundred of Norfolk a report of the state of the
corn supply of the poor was received, and some arrangement of this
d. Other special
methods of
providing food for
the poor.
2. Evidence as to
success or failure of
the corn
regulations.
kind is usually reported. In some hundreds two degrees of poverty
were recognised. The very poor only paid half-a-crown a bushel for
their barley, but "the labourers yt
had nott so much neede" were
served at three shillings[446].
This plan does not seem to have been general in Yorkshire, but it
was adopted by at least eight hundreds[447]. There are moreover
many examples of stores of this kind in Hertfordshire and some in
every Eastern county except Northumberland and Lincolnshire[448].
The fact that special mention is made of poor labourers shows that
relief was not confined to the disabled or to paupers. It was given in
the eastern counties more than in the western probably because the
scarcity was more felt in the east and the poor were in greater
distress[449].
Sometimes other plans were adopted. The owners
and dealers of corn were expected to contribute to
the need of their less fortunate neighbours. At
Reading the corn masters set apart a sack in every
load to serve for the poor at twelvepence a bushel under the market
rate[450]. It would seem that some allowance was usually made by
dealers in corn, for another dealer who was a victim of a riot at
Woodchurch states that out of ten quarters he left five to be sold to
the poor[451].
Other expedients of this kind were adopted; in Devonshire the
children of the poor were billetted on those able to give relief[452],
and at Maidstone the town baked the bread and gave loaves to the
day labourers and poorest inhabitants[453]. Three of the hundreds of
Cambridgeshire tried a still more organised plan: "the poorer sort
had weekly corne delivered to them at home at twelvepence in the
bushell in the least under the market prices[454]."
We have very varied opinions as to the success or
failure of the organisation for supplying the poor
with corn. The justices in several instances state
that the search raised prices, and ask that a
second search may not be made[455]. In a few cases they say the
regulation of the markets was injurious. The most decided of these
is an account from Edwinstree and Odsey, "And we humbly
conceaue that or
strickt lookeing to the marketts by or
selves and
others, very sufficient and diligent supervisors
, whom we haue
imploied wth
a great deale of care in these businesses is an occacion
that the marketts are the smaller, the corne dearer and new shifts
and devises are found out[456]." In the autumn of 1631 inquiries as
to the cause of the scarcity were instituted, and the Bridport
authorities candidly replied that it was owing to the interference of
the justices[457]. But perhaps the most interesting protest is that
from Chipping Wycombe. It was a town on the borders of
Buckinghamshire, which was largely inhabited by dealers in corn and
was the market for the neighbouring parts of Oxfordshire and
Berkshire. After the instructions of the Privy Council had been
followed, only a quarter of the usual quantity was brought to the
market. The dealers, the Mayor tells us, lost heavily because the
price of meal had been fixed by the Lord Mayor, and both they and
the farmers were disgusted at the lowering of prices in other parts of
the country. Formerly the badgers had set aside sacks for the poor,
and the farmers and others had provided stores for them. This they
now refused to do, but the justices did their best and themselves
sold to the poor under the market rates[458]. The dislike of the
orders is very apparent in this report, but it bears witness to the fact
that they were sometimes successful, since prices had been lowered
in consequence in other parts of the country. But as Chipping
Wycombe was inhabited largely by corn-dealers, and as it drew its
supplies from other counties, the orders failed there, and the fact
that Chipping Wycombe was such a town may have been not
without its influence on the making of history, for John Hampden,
we are told, was one of the justices present who witnessed the
distress of this disastrous market-day. It was not a position in which
he would judge favourably of the effects of governmental
interference.
Still the balance of evidence is in favour of the orders. When they
were first put in force they seem to have had a considerable effect in
lowering the price. Many of the reports sent in during the last half of
December and beginning of January tell us that this was the
case[459], though after the beginning of the year prices again rose,
because the corn was wanted for seed as well as for food. However
even as late as April 30th a report from the district of Horncastle in
Lincolnshire informs us that the writers have ordered the markets to
be furnished every week with a particular quantity, and that the
price of oatmeal, which was the chief food of the poor in that part of
the country, had been lowered from eight groats to one shilling and
tenpence[460].
There are other statements of the same kind[461], but one of the
most strongly expressed of these is from the justices of Suffolk, "We
giue yr
lo(rdshi)ps many humble thanks for your great fauours
shewed unto vs and to the whole state of this county in these
necessiteouse times by those most prudent, compassionate and
charitable considerations deliuered in your bookes of directions and
sent vnto vs wch
we haue wth
our uttermost endeauours laboured in
euery parte to see accomplished as well by or
selues as others. And
we must acknowledge with or
and the countryes great thankfulnesse
unto yr
lo(rdshi)ps that ye
benefit wch
hereof hath arisen hath bine
beyonde all expectation inestemable and of wonderful effect[462]."
But the strongest argument that on the whole these measures were
beneficial is to be found in the fact that they were enforced
throughout the country by the justices with very few protests. The
justices would as a rule be landlords and generally corn owners; the
regulations were against their interests, and, unless they had
thought that they contributed to the public welfare, they would have
complained more and performed less. When they thought a course
objectionable they said so: many of them did not approve of a
second search of the stocks of corn[463]; in several instances they
said that the order to prevent millers from buying corn was not
beneficial, because the millers sold in small quantities to the poor
who did not come to market[464]. But the rest of the orders
3. Reasons for the
adoption of the corn
regulations.
4. Bearing of the
scarcity measures
concerning corn were enforced nearly always without comment or
with approval.
It is not difficult to see reasons for the success of
such an organisation. Corn fluctuated violently in
price because of the narrowness of the area from
which the supplies came. Even with our own worldwide supply a
corner in wheat has been attempted and for a time maintained.
When little corn was imported into England, and even counties were
largely self-supporting, farmers might easily raise the price by
keeping back their corn from market[465].
But the great price was not always the worst of the trouble. The
justices of Devonshire tell us that corn could not be had for money,
and the statement is confirmed by Fitz-Geffrie in his Curse of Corne-
horders, "O miserable condition! the poore man is put to a double
labour, first to get a little money for Corne and then to get a little
corne for money & this last is the hardest labour; he might haue
earned almost halfe a bushell while hee runnes about begging to
buy halfe a pecke[466]."
We must remember the narrowness of the market; the excessive
fluctuations in price, and the difficulty of finding a seller willing to
sell a small quantity of grain, before we can criticise fairly the
organisation which was established during these years of high-priced
corn.
In any case the corn orders of the Government seem to have helped
to maintain the public peace. In 1527, in 1551, in 1587, in 1597, and
in 1623 the rise in the price of corn immediately occasioned
disorder[467], and even in 1630 attacks were made on the carts
carrying corn, and there were other signs of disturbance[468]. But in
this last season of scarcity there was no serious outburst. The orders
of the Government probably relieved the distress and certainly
helped to convince the people that their rulers were trying to help
them.
on the history of
poor relief.
a. The training of
the justices.
b. The standard of
comfort of the
poorer classes.
The organisation for supplying the poor with corn
in 1631 is both indirectly and directly connected
with the history of poor relief. We have already
seen that the orders for supplying corn seem to
have suggested the orders for the ordinary relief
of the poor, and that both sets of orders were worked by similar
methods. The season of 1630-1 is the first in which the
administrators seem to have properly fulfilled their duties. Then the
commands of the Government seem to have been vigilantly
enforced. This was not always easily accomplished, rebellious
inhabitants were coerced, negligent justices were punished[469]. But
on the whole the justices seem to have worked with zeal, and the
success obtained by them during this exceptional crisis must have
made it easier for them to cope with the relief of the poor in more
ordinary times.
Moreover the direct relief afforded by the corn
stores must be taken into account when we
attempt to estimate the amount of comfort
enjoyed by the manual workers in the reign of Charles I.
Prof. Rogers has compared the condition of the labouring population
at different times by estimating the amount of food which could be
bought by a labourer receiving average wages in each period. This
method of comparison leads him to the conclusion that the majority
of the population were in a very miserable condition before the
outbreak of the Civil War[470].
But in 1630-1, and to some extent also in 1623, labourers did not
pay the market price for their food, and this fact must modify any
conclusion derived from such a source so far as the reigns of James
I. and Charles I. are concerned. Not only was corn sold under price
from public granaries and stores, but it is probable that whenever
arrangements were made to serve the labourers at home the prices
were somewhat reduced, as the sellers would then be saved the
trouble of taking the corn to market, and the expense of paying the
market tolls.
5. Provision of fuel
for the poor in
Winter.
Moreover it has often been pointed out that the relative comfort of
any class can be better ascertained if we consider the earnings of
the family rather than those of the individual[471]. This was a period
in which women could easily obtain work in spinning and when
children were apprenticed at an early age, and so required little
support from their parents. For these reasons it seems likely that the
labourer of the reign of Charles I. would be better off than the
amount of his wages would lead us to suppose, and this estimate is
confirmed by the scale of diet fixed for the boys in the Children's
Hospital of Norwich in 1632.
The boys in the hospital were between the ages of ten and fourteen.
For dinner they were always to have six ounces of bread and a pint
of beer: three days in the week they had also a pint of pottage and
six ounces of beef, and on the remaining four an ounce of butter and
two of cheese. For supper they had always six ounces of bread, a
pint of beer, an ounce of butter and two of cheese, and for breakfast
every day three ounces of bread, half an ounce of butter and half a
pint of beer[472]. As this represents the food of the destitute orphans
of Norwich it is not likely to be much better than the usual standard
of the poorest class, and seems to compare very favourably with the
food of a boy in the same class in our own time. The ordinary
standard of living thus does not appear to be miserable, but the poor
must have suffered terribly, if there had been no exceptional relief,
whenever there was no work for them to do, and when corn was
double the usual price.
It is these fluctuations that were the chief source of misery, and by
lessening their effect the scarcity measures of the time were of
enormous importance to the whole of the labouring class.
But relief in times of emergency was afforded to the needy in other
times of exceptional distress.
In Winter fuel was provided. Thus at St Albans,
wood was bought for the poor in the reign of
Queen Elizabeth[473]. In London there was a coal
yard before 1590, and early in the reign of James I. the City
6. Help in times of
sickness and
plague.
authorities obtained permission to import four thousand chaldron of
"sea cole" free of duty for the purpose of supplying those in need of
help[474]. Payments for fuel formed part of the regular organisation
at Norwich[475], and directions to secure a supply to the poor of
their district are contained also in the orders to the overseers of
1623[476]. This provision is another illustration of the fact that a
great deal of the relief given was designed to protect the people
from excessive fluctuations in price.
Methods of relieving the poor in times of sickness
were also numerous. The Great Plague of London
was not an isolated attack; throughout the
seventeenth century few years pass without an outbreak in one of
the large towns. Special orders were drawn up to prevent the spread
of infection; watchmen were appointed to guard stricken houses,
and the inmates for the time had to be supported by the
community[477]. The cost of this severely taxed local resources. At
Cambridge we hear that in 1630, 2800 claimed relief and only seven
score were able to contribute. In this case a brief was issued
authorising collections from other parts[478], and London and
Norwich sent generous contributions[479]. One town seems to have
helped another frequently when this scourge broke out: New Sarum
sent aid to London, Norwich to Yarmouth, and both New Sarum and
Bury thanked the Londoners for the help they had themselves
received under like circumstances[480].
Pest houses were often established; at Reading eight were built, and
we hear of their erection in Norwich, London, Cambridge and
Windsor[481]. The way the funds were raised for the plague-stricken
poor of Windsor is one of the many illustrations of the fact that
private charity and public rates were often used for the same
purposes and administered by the same officials. The site for the
pest house was given by an alderman, some of the money was
raised for the relief of the infected poor "by way of taxation," part
was given by gentlemen of the neighbourhood, and the rest was
probably paid out of the town chest[482]. At Hitchen and in other
7. Contributions to
sufferers from fire.
places relief was given to the plague-stricken by means of the poor
law organisation[483].
The Privy Council frequently made orders connected with the plague.
Sometimes they ordered the erection of pest houses, sometimes a
special collection. In Grantham and Worcester the rich fled from the
infected town, so that government was at a standstill; the absentees
were required to pay double rates and, if necessary, to return and
help govern the town[484]. At another time the paper-makers in
Suffolk were prevented from working because of the plague, and a
special collection was ordered for them[485]. All these orders
illustrate the paternal nature of the Privy Council government, and
also seem to show that in social matters it was exercised in favour of
the poor.
But not only in time of plague was provision made for the sick. At
Norwich it was part of the regular organisation for the poor; in
London St Thomas's and St Bartholomew's hospitals were already in
existence, and in most towns there were numerous lazar houses. In
some places the help provided was even greater than that of to-day;
a town physician was appointed especially to look after the poor.
Newcastle adopted this plan in the reign of Elizabeth, and the
practice was continued down to the time of the Civil War, and in
1629 a "learned physician" was engaged by the Mayor and
Corporation of Barnstaple to give advice gratis to the poor[486]. This
happened just at the time when, as we have seen, there was great
activity in matters connected with the poor, and is an illustration of
the fact that the duties of the seventeenth century municipality were
very various, and that even in 1629 the town authorities were
sometimes pioneers in matters concerning the poor.
Fire was another way in which sudden loss was
caused to large numbers of people. Houses were
still built largely of wood and often very close
together. Whole towns were not infrequently destroyed. Tiverton
suffered twice in this way, and the suddenness of the calamity to so
flourishing a town seems to have especially struck men's
8. Characteristics of
seventeenth century
poor relief.
a. Little distinction
between paupers
and non-paupers.
imagination. "He which at one a clocke was worth fiue thousand
pound and as the Prophet saith drunke his Wine in bowles of fine
Siluer plate, had not by two a clocke so much as a woodden dish left
to eate his meate in, nor a house to couer his sorrowfull head"[487].
In the second destruction of 1612 three hundred of the poor people
were boarded in the shire, and collections to rebuild the town were
made throughout the country. Similar disasters happened to several
other towns, to Dorchester in 1613 and Hertford in 1637, and like
collections were made for them among charitable people.
1632: "Paid Mr Henderson the townes physician his ½ yeares
stipend due at lady-day 1632, 20l." A payment of £10 was also made
in 1647, to "doctor Samuel Rand the townes physition." M. A.
Richardson's Tracts, Vol. III. p. 47. Extracts from the municipal
accounts of Newcastle. Barnstaple, Nov. 24th, 1629: "Dr Symes a
learned Physician engaged by Mayor and Corporation to be resident
in town and give advice gratis to the poor at £20 per annum for two
years to be paid out of town stock if not raised by subscriptions."
Wyot's Diary, Barnstaple Records, North Devon Herald, April 21,
1881.
Relief was also given to individuals who suffered loss from fire,
sometimes by means of authorised collections and sometimes out of
the public funds[488]. Thus in the North Riding £20 was paid to
twelve persons of Thornton and Farmanby, on account of their losses
caused by fire[489].
Thus in the first half of the seventeenth century
relief in times of emergency forms a considerable
part of the assistance given to people in distress.
That provided in years of high priced corn was not
distributed only to those who were usually
paupers but to the whole of the labouring class;
that afforded in times of fire or sickness affected all classes of the
community. There was thus much less difference between paupers
and the rest of the community than there is to-day. All classes were
relieved because poor relief was originally part of a paternal system
b. Little distinction
between relief
afforded by
voluntary donations
and that provided
by poor rates.
of government under which the rulers regarded the maintenance of
the usual prosperity of every class as a part of their duties. There is
a curious case of landlord and farmer relief during the season of
plenty in 1619. It was then stated that of late years there had been
so much corn that the farmers were impoverished. A letter was
therefore sent to the justices of every county ordering them to
confer concerning some fit place where a magazine might be
provided for storing a quantity of corn. The reason for this is stated
to be that it is the "care of the state to provyd as well to keepe the
price of corne in tymes of plenty at such reasonable rates as may
afford encouragemt and lively good to the farmer and husbandman
as to moderate the rates thereof in time of scarcitie for the releefe of
the poorer folke"[490]. Few regulations could make it clearer than
this, that the paternal measures of the Government were not
confined to one particular class, but affected the whole of the
community.
The distinction between paupers and non-paupers
therefore was much less clear than it is to-day,
and it is also true that the distinction between
voluntary contributions and compulsory poor rates
was much less rigidly defined. The supply of the
poor with corn is nearly always stated to have
been a voluntary measure, but it was carried out under very
considerable pressure from the justices. Sometimes the pressure
amounted to compulsion. Thus in the Sarum division of Wiltshire
some gave "franklie and freely good quantities of their store" to the
poor but others were "wilfull." The justices "terrified them a little wth
conventing them before the Lords of the Counsell and then they
seemed very willing and tractable"[491]. It is difficult to say therefore
how far the corn charities of the time were voluntary and how much
they were compulsory. There was also a close connection between
private and public charity in other forms of relief.
Probably in every town there were numbers of endowed charities
controlled by the municipal officers or by overseers or by some
public or semi-public authorities, which were practically a part of the
same system as that enforced by law. Such were the four royal
hospitals of London and the hospitals of Gloucester and Norwich.
Such also were the many almshouses under the management of
corporations, as were the almshouses founded respectively by Leche
and by Kendrick at Reading, and the many charities for apprenticing
poor children and lending money to poor tradesmen, which we shall
afterwards consider in detail. Sometimes the connection was closer
still, and the workhouse like the Free Library of to-day might be
partly provided by private generosity and partly by public rates. Such
was the case with the Barnstaple workhouse and the Jersey school
of Newark[492].
The relief of the poor in times of emergency thus brings into
prominence two of the main features of the poor relief of the time.
First, that the public compulsory system was developed from a
voluntary system and that in the seventeenth century voluntary and
public poor relief were closely connected. Secondly, that the poor
relief of the time was intimately connected with the general system
of government under which all classes were compelled by
Government to do their duties and any class might be relieved that
for the time failed to obtain its usual degree of prosperity.
The Rust Programming Language 2nd Edition Second Converted Steve Klabnik Carol Nichols
CHAPTER XI.
METHODS OF RELIEF, 1597-1644 (continued).
B. Ordinary Relief.
α. Impotent poor.
1. Almshouses and endowed charities.
(a) Old endowments which remained
unchanged through the Reformation.
(b) Old endowments regranted to the
Corporation or other public body.
(c) Fresh endowments.
(d) Pensions and gifts from endowed
charities.
2. Provision for the old from compulsory
rates.
(a) Relief from the county by pensions
paid to soldiers and sailors and by
hospitals maintained by county
funds.
(b) Relief from the parish by pensions
paid to the destitute, by the grant of
a house, or by arrangements for free
board and lodging in the house of
some parishioner.
β. Children.
3. Provision for children by apprenticeship.
(a) To masters. (b) To the masters of
the Bridewells or industrial schools of
the time.
α. The impotent
poor.
1. Almshouses and
endowed charities.
a. Old endowments
which remained
unchanged through
the Reformation.
4. Schools for little children and
orphanages.
γ. Able-bodied poor.
5. Relief given to prisoners.
6. Provision of funds to provide work for
the unemployed.
7. Methods of providing work.
(a) Stocks used to employ the poor in
their homes or elsewhere.
(b) Introduction of new trades.
(c) Workhouses and Jersey schools.
(d) Bridewells.
(e) Emigration.
(f) Pressure on employers.
(g) Advancement of capital without
interest.
We have seen how the poor were relieved in times of special
emergency; we will now examine the kind of help that was
bestowed upon those classes of poor who in almost every
community were more or less constantly in need of assistance. We
will notice first the relief given to the impotent and aged poor;
secondly, the measures adopted to provide for destitute children;
and lastly, the methods used to find work for the unemployed or to
suppress vagrants.
The method of relieving the
impotent poor differed very
considerably from that with
which we are familiar. The workhouses of the
seventeenth century were mainly places for people
who could work, the aged and impotent poor were
often relieved by almshouses controlled by public and by private
authorities, but founded and maintained by private liberality. It was
indeed an age in which almshouses or hospitals as they were often
called abounded. Probably there were nearly as many in existence
then as there are to-day, in spite of the fact that our population has
1 b. Old
endowments
regranted to the
Corporation or other
public body.
increased sixfold. Some of these hospitals were old endowments that
had survived the Reformation; others had been dissolved with the
other religious houses and regranted to the municipal authorities of
the place to which they belonged; many more were founded during
the reigns of Elizabeth, James I., and Charles I.
The well-known Hospital of St Cross at Winchester is a good
example of an old foundation that has had a continuous existence
from its first endowment in the middle ages until the present day.
The modern tourist, like the wayfarer of mediæval times, may
partake of the refreshment provided by its ancient regulations, and
may still receive his bread and beer like a seventeenth century
beggar. But it has also been an almshouse since the time of Henry
II. By the Charter of Foundation "thirteen poor men, feeble and so
reduced in strength, that they can scarcely, or not at all, support
themselves without other aid, shall remain in the same hospital
constantly; to whom necessary clothing, provided by the Prior of the
Establishment, shall be given, and beds fit for their infirmities; and
daily a good loaf of wheaten bread of the weight of five measures,
three dishes at dinner and one for supper, and drink in sufficient
quantity[493]." This hospital was not dissolved by Henry VIII. but
continued under its old regulations throughout the Reformation.
Laud ordered inquiries to be made concerning it shortly after 1627,
and the thirteen pensioners were then maintained with full
allowances[494]. Many hospitals survived the dissolution besides St
Cross and remained in private hands; a few like St Giles's, Hereford,
or St Bartholomew's at Sandwich had been governed by the town-
rulers from the time of their foundation[495], and these for the most
part retained their old endowments and remained under municipal
management.
Other hospitals were regranted to the
Corporations of their respective cities and towns
soon after the dissolution in the same way as St
Bartholomew's had been given to the City of
London. Such was the case with St Bartholomew's
of Gloucester. Queen Elizabeth stipulated that some of the payments
formerly made by the Crown should be remitted, but placed the rest
of the revenues in the hands of the Corporation on condition that a
physician and surgeon and forty poor people should be there
maintained[496]. Two other of the ancient hospitals of Gloucester
came into the hands of the Corporation. One of these, St Margaret's
Hospital, provided for ten poor men in 1562, and was then governed
by the town authorities; the other, St Mary Magdalen, was granted
to the city both by Queen Elizabeth and King James, and was called
King James's Hospital[497]. Even if a hospital came into private
hands it often returned to its original purpose. Sentiment as to its
rightful use was probably very strong in the case of any institution
which had been founded to do a work which obviously needed
doing. Thus Kineburgh's, another of the old hospitals of Gloucester,
had been sold at the dissolution to a Mr Thomas Bell, and was
afterwards refounded by him and placed under the care of the
Corporation. His donation was confirmed by Queen Elizabeth, and
during the reign of James several other small endowments were
added by various donors for the maintenance of the poor there[498].
Gloucester was perhaps especially fortunate in retaining so many of
its old endowments, but elsewhere similar arrangements were made.
St Giles's of Norwich, St Leonard's of Launceston, St Edmund's of
Gateshead, St Thomas's and St Catherine's of York, St Mary
Magdalen's of King's Lynn, and Trinity Hospital of Bristol were all old
foundations which, during the sixteenth and seventeenth centuries,
came into the hands of the corporation of the town to which they
severally belong[499]. St Giles's Hospital of Norwich may be taken as
an example of these re-established hospitals. According to the
Letters Patent of Edward VI. it was granted to the Mayor and
Corporation of Norwich, and was to be called the House of God or
the House of the Poor: forty men and four matrons were to be
provided for; they were to receive bed and bed-clothes, bread,
meat, drink and firing. The pensioners were not appointed for life,
but were removable from week to week or from day to day[500]. This
hospital therefore was very much like a modern workhouse, except
that it was supported by endowments or by voluntary subscriptions.
1 c. Fresh
endowments.
Occasionally these ancient charities came to be managed by the
vestry. Thus in Bristol there were three old endowments of this sort.
Redcliffe almshouse was supposed to have been established about
1440 by the famous Bristol merchant William Canninge; the Temple
Gate almshouse and Burton's were probably foundations of an even
earlier date. The two former were governed by the vestry of St Mary,
Redcliffe, and long before 1821 had become simply houses in which
aged paupers were placed by the overseers[501]. Burton's almshouse
was governed by the vestry of St Thomas's parish, and was used as
an almshouse from which paupers were not excluded. These
institutions had thus then become part of the compulsory and legal
system of poor relief rather than of the voluntary charity which
existed by its side.
But not only were there many old foundations for
helping the aged poor, but the century from 1550
to 1650 was itself the great time of the foundation
of new almshouses. It is rare to find a town of any size in which
some institutions of this kind were not established during these
years, though in country parishes they were not so frequent. They
were governed in many different ways, but generally by some public
body or by some set of men closely connected with the authorities
who were responsible for the administration of poor-relief. Some
were governed by the Corporation like the small almshouse founded
by Fox at Beverley. Many resembled the Temple Hospital at Bristol;
this was endowed by Sir Thomas White and was vested in trustees
who were members of the Corporation. A few were managed by
merchant or craft companies associated with the government of the
town; such was the case with the Merchants' Hospital of Bristol and
Dame Owen's almshouses in Islington. Others were in the hands of
private trustees sometimes connected with the founder's family, at
other times with his position. The Archbishops of Canterbury were
generally associated with some of the favourite charities of the time.
Grindal provided a stock for setting the poor to work, Abbot a
workhouse, Laud apprenticeship endowments, and Whitgift an
almshouse at Croydon for twenty-eight poor people, the government
1 d. Pensions and
gifts from endowed
charities.
of which he vested in his successors in the see of Canterbury. These
hospitals were usually filled by the aged and impotent of the poorer
classes. But occasionally they also supplied the wants of the poor in
a better social position. The Charterhouse of Colonel Newcome fame
was a foundation of the reign of King James, and supplied a refuge
for eighty poor gentlemen, merchants, soldiers, or mariners.
Altogether the almshouses of the time formed a very important part
of the provision for the poor. In some towns like that of
Hereford[502] they were extremely numerous. Other places like
Morton Hampstead seem to have established a public almshouse for
the poor, but as a rule these institutions were privately endowed,
and the help given by them was thus free from the sting that is
attached to legal and compulsory charity.
But besides the almshouses many other charities
were founded to help the aged poor, some of
which have proved of doubtful benefit to their
successors. Many pensions and gifts of small amount were
distributed by public or semi-public bodies. The City Companies of
London frequently received bequests of this kind. Thus the
Clothworkers administer the gift of Sir Thomas Trevor. In 1622 he
bequeathed £100 in order that six poor women might have 20s. a
piece in quarterly instalments. At Bristol every week some one poor
widow receives 10s. from Mr Whitson's charity, and two poor
householders have 20s. each, though neither widow nor householder
can have the gift more than once in the same year[503].
Innumerable smaller charities also exist in particular towns and
parishes ordering the distribution of sixpences and shillings on
particular Sundays or Feasts, or after the hearing of some sermon.
Even more frequently bread charities were established. Thus in
Hereford Cathedral twelve poor people receive a loaf every Saturday,
and sixpence on twelve of the principal feasts and vigils of the
year[504]. Sometimes so many poor men or women are "apparelled,"
or gowns, shirts and smocks are bought and distributed: more often
fuel and wood are provided[505]. Bequests of this kind are very
2. Provision for the
old from
compulsory rates.
2 a. Relief provided
by county funds.
2 b. Relief of the
aged by means of
pensions from the
parish or by the
provisions of houses
numerous, but the amount of relief afforded to each individual is
often ridiculously small. Still the value of money was three or four
times greater then than it is to-day, and a pension of 10s. or 20s.
was a much greater contribution towards the maintenance of the
poor person. Moreover, parochial authorities and officials of City
Companies had comparatively few people to deal with, and it was
possible for them to know something about the recipients of these
charitable doles.
Altogether the number of endowed charities which afforded
assistance to old people was large in the seventeenth century in
comparison with the number of persons who were in need of relief.
Moreover, new almshouses were continually founded throughout this
period and until the close of the century. Probably many of these are
in existence to-day, but there has been no increase at all
proportionate to the growth of the population, while a few of the old
institutions like the Redcliffe almshouse at Bristol have become part
of the legal system of relief while others have disappeared
altogether[506].
But although the aged poor
were largely relieved by
almshouses there were still
many who were provided for by the legal and compulsory system.
Some hospitals were supported by the county funds. There were
several in the North Riding of Yorkshire which were used as
almshouses for the impotent and aged poor and received grants
from the County Treasurer[507].
Aged soldiers and sailors were also provided for not by the parish
but by the county. As we should expect this was found to be a heavy
charge in Devonshire, and the magistrates grumbled at the amount
they had to give for this purpose[508].
More often the aged poor were relieved by the
funds raised by the parish. Two methods seem to
have been adopted. The most usual was what we
should now call a system of out-relief. Pensions
or free board and
lodging.
β. Children. 3 a. Apprenticeship
to masters.
were granted varying in amount from threepence
to two shillings a week, but generally about one
shilling[509]. Sometimes in addition rent was paid and often
habitations were provided which were built by the overseers on the
waste[510]. But the poor in these were not under any special control
but were allowed to look after themselves in other respects. In some
parishes, however, instead of receiving weekly pensions the poor
were billeted on the rich. In a report from the district of Furness and
Cartmell, one hundred and seventy-six people were relieved in this
manner, and two hundred and eighty-eight by means of pensions. In
this case each parish adopted one method or the other exclusively;
thus in Alythwaite thirty-nine poor were billeted, in Coniston twelve
were provided for by money payments[511]. In other cases the
method of billeting existed as an exceptional practice side by side
with the pension system. Thus in Staplegrove, Somerset, in 1599,
after the list of payments given for the poor, there are the names of
two men, each of whom kept a poor impotent person in his
house[512].
The parochial system of the time was therefore mainly a system of
out-relief and sometimes free lodging, but it was modified by a
practice of "boarding out" the aged. It was of considerably less
importance than it is to-day because the amount of endowed
charities bore a much greater proportion to the number of old who
were to be relieved.
We will now consider the main
methods of providing for the
young. Compulsory education does not seem to be
peculiar to the nineteenth century. In the reign of Charles I. all
children had to be taught to work and trained to a trade. The
method chiefly employed was that of apprenticeship. But schools,
training homes and orphanages also existed in which children
received the technical education of the time. Parents were obliged to
apprentice their children or put them into service as soon as they
were old enough. If the parents were able they paid the preliminary
fee themselves; if not, the parish found masters for the children, but
in this case they often had to work at the more unskilled trades.
Sometimes money was paid for the pauper apprentice as for any
other child, but at other times men were forced to keep the children
without payment. There was often, as we should expect, a great
deal of friction in the matter. In a report from Yorkshire, signed by
Lord Fairfax, we are told that the justices do their best to find
masters and keep the children with them, but that there was
considerable difficulty in so doing[513]. Elsewhere there are also
hints that the masters wished to free themselves from any burden of
the kind[514], but there is much to make us think that on the whole
the method at this time worked well. It was apparently the favourite
remedy for the time for the evils of poverty. The writers of the legal
handbooks insist that it was an especially important part of the duty
of overseers[515], while throughout the seventeenth century
numerous bequests for the purpose were left by private
persons[516]. This is very strong evidence that the philanthropists of
the time thought that the binding of poor children apprentice was an
excellent way of providing for their maintenance and training. Laud
himself was especially interested in the matter. In his own lifetime he
made a gift for the purpose of apprenticing ten poor boys of
Reading[517], and either during his lifetime or by his will he also
provided funds for the same object in Croydon, Wokingham, Henley,
Wallingford, and New Windsor[518]. Moreover the Privy Council
appear to have specially enforced this part of the relief of the poor
and to have demanded and received more detailed reports on this
subject than on any other. This action of the Privy Council and the
number of these bequests therefore make us believe that the evils of
pauper apprenticeship were not very prominent in the seventeenth
century. No doubt the fact that it was then the usual custom for an
apprentice to board with his master and not a practice chiefly
confined to children brought up by charity, made a great difference.
Both kinds of apprentices were bound in the same way and would
tend to be dealt with in the same manner. The selection of the
master would make the principal difference; and the welfare of the
apprentice would depend upon the care taken by the administrators
3 b. In the
bridewells, or
Industrial schools of
the time.
of the charities and the parochial funds in providing masters for the
children.
The picture in the Fortunes of Nigel of Jenkin Vincent, the London
apprentice of this time brought up at Christ's Hospital, could not
have been very unlike the reality. Great hardship must have been
inflicted in some cases[519], but when the practice was new and the
custom general, the apprentice bound by charitable funds would not
usually be treated much worse than other apprentices. Otherwise it
is not probable the Privy Councillors in their public capacity, and an
Archbishop and many other charitable people in their private
capacities, would have taken so much trouble to extend this practice
by finding the funds for the purpose of thus providing for the
maintenance and education of poor children.
But not all destitute children were bound
apprentice to masters in the town. The bridewells
or workhouses of the time had often a special
children's department which seems to correspond
with our own Industrial schools.
The London Bridewell had thus two distinct functions to perform. On
the one side it was a House of Correction, on the other it was a
technical school for young people. Sometimes the orphaned sons of
freemen were received there, at other times children were sent by
the overseers of the parishes, and often young vagrants were
brought in from the London streets. They were trained in very
various occupations: a full report of the hospital was drawn up in
1631, and we are then told that "four silk weavers keep poore
children taken from the streets or otherwise distressed, to the
number of forty-five."
There were also more than a hundred others at that time in the
Hospital who were apprenticed to pinmakers, ribbon weavers,
hempdressers, linen weavers, and carpenters[520]. Christ's Hospital
at Ipswich, the Hospital at Reading, and the Nottingham House of
Correction, had all training departments of this kind in which many
of the poor children of these towns were taught trades.
4. Schools for little
children and
orphanages.
Besides all this, children who were too young to
be apprenticed were in many places taught to spin
and sometimes to read and write. We have seen
that in Norwich in every parish "a select woman" was appointed for
this purpose in the reign of Queen Elizabeth, and in 1630 a similar
order was made to the effect "that a knittinge schooledame shalbe
provided in every parishe where there is not one already, to sett
children and other poore on worke[521]." Even in the hamlets like
those of Whitwell and Sellside, in the county of Westmoreland, three
poor boys were maintained at the school by the parish who were to
be taught trades as soon as they were old enough[522]. In
Hertfordshire we are told that many had been placed as apprentices
"and such as are not of fitt yeares to bee put forth wee haue caused
to bee sett to spinning and such smale worke as is most meete for
them according to the tendernesse of their age that idlenesse may
not fasten in them[523]."
These schools were not improbably very numerous. In documents
containing the instructions of justices to overseers knitting schools
were advocated. Thus in directions issued in 1622 by some of the
justices of Norfolk for the hundreds of Eynesford and South
Erpingham, the justices resolve "that poore children be put to
schoole to knittinge and spinninge dames and the churchwardens
and ouerseers for the poore to paie the schoole dames their wages
where the parents are not able[524]."
All this points to a system of popular education of the kind then
approved.
In the largest towns orphanages also were established about this
time. Christ's Hospital in London, as we have seen, was originally
established for the little children of the London streets. During this
period there were from seven to nine hundred children maintained
at the cost of this institution, some in London and some at nurse in
the country[525]. At Bristol there were two establishments of the
same kind. Queen Elizabeth's Hospital was founded by a citizen
named John Carr after the model of Christ's Hospital in London. The
γ. The able-bodied
poor.
5. Relief given to
prisoners.
boys were subject to the same regulations and still wear the same
blue and yellow dress[526]. The Red Maid's School was endowed by
the will of John Whitson in 1621. It was to consist of a matron and
forty girls. The children were to learn to read and sew and do such
other work as the matron and the Mayor's wife should approve.
They were to be apprenticed for eight years, to wear clothes of red
cloth, and attend on the wives of the Mayor and aldermen on state
occasions[527]. In Plymouth, Exeter, and Norwich also there were
similar institutions, but they seem to have only existed in the large
towns. Both in the country and towns orphaned and deserted
children were generally "boarded out" until they were old enough to
be apprenticed, and payments were made for them from the rates
amounting to about a shilling a week.
Children were thus very well provided for, and their training was
considered a matter of national concern. Parents, whether they were
very poor or not, were compelled to send their children to work or
school and either to apprentice them or to find situations for them.
We are apt to consider popular education an exclusively modern
movement, but in this, as in many other matters, the aims of the
seventeenth century anticipate those of the nineteenth. They had
ideas which were very different from those of to-day as to the kind
of training which was necessary, but they attached an equal
importance to the necessity of training. The Town Council of Norwich
and the justices of Hertfordshire and Norfolk took energetic action in
the matter.
We will now see how the administration of the
time affected the able-bodied poor. The help given
to the unemployed is by far the most important
part of this relief, but some aid was also given to
prisoners.
The prisoners of the sixteenth century must have suffered great
hardships. No adequate means seem to have existed for their
maintenance. Their friends supported them, and under certain
regulations they were allowed to beg. Several statutes made in the
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.
More than just a book-buying platform, we strive to be a bridge
connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.
Join us on a journey of knowledge exploration, passion nurturing, and
personal growth every day!
ebookbell.com

More Related Content

PDF
The Rust Programming Language Second Edition 2 Converted Steve Klabnik
PDF
The Rust Programming Language 2nd Edition Steve Klabnik
PDF
The Rust Programming Language 2nd Edition Steve Klabnik
PDF
The Rust Programming Language Steve Klabnik
PDF
(Ebook) The Rust Programming Language, Second Edition by Steve Klabnik, Carol...
PDF
The Rust Programming Language, Second Edition Steve Klabnik
PDF
Download Complete The Rust Programming Language 2nd Edition Steve Klabnik PDF...
PDF
The Rust Programming Language Steve Klabnik
The Rust Programming Language Second Edition 2 Converted Steve Klabnik
The Rust Programming Language 2nd Edition Steve Klabnik
The Rust Programming Language 2nd Edition Steve Klabnik
The Rust Programming Language Steve Klabnik
(Ebook) The Rust Programming Language, Second Edition by Steve Klabnik, Carol...
The Rust Programming Language, Second Edition Steve Klabnik
Download Complete The Rust Programming Language 2nd Edition Steve Klabnik PDF...
The Rust Programming Language Steve Klabnik

Similar to The Rust Programming Language 2nd Edition Second Converted Steve Klabnik Carol Nichols (20)

PDF
Advanced Swift Updated For Swift 5 Chris Eidhof
PDF
Apidays Paris 2023 - Forget TypeScript, Choose Rust to build Robust, Fast and...
PDF
7li7w devcon5
PDF
Who go Types in my Systems Programing!
PDF
Software Engineering Thailand: Programming with Scala
PDF
robert-kovacsics-part-ii-dissertation
PDF
DEVCON1 - BooJs
PDF
Eloquent JavaScript Book for Beginners to Learn Javascript
PDF
EloquenFundamentalsof Web Developmentt_JavaScript.pdf
PDF
Scala - from "Hello, World" to "Heroku Scale"
PDF
Reason - introduction to language and its ecosystem | Łukasz Strączyński
KEY
LISP: How I Learned To Stop Worrying And Love Parantheses
PDF
Programming Languages: some news for the last N years
PDF
The Scala Programming Language
PDF
(eBook PDF) Starting Out with C++: From Control Structures through Objects 8t...
PDF
The Rust Programming Language: an Overview
PDF
(eBook PDF) Starting Out with C++: From Control Structures through Objects 8t...
PPTX
MozillaPH Rust Hack & Learn Session 2
PDF
Starting Out with C++: Early Objects 9th Edition by Tony Gaddis (eBook PDF)
PDF
scalaliftoff2009.pdf
Advanced Swift Updated For Swift 5 Chris Eidhof
Apidays Paris 2023 - Forget TypeScript, Choose Rust to build Robust, Fast and...
7li7w devcon5
Who go Types in my Systems Programing!
Software Engineering Thailand: Programming with Scala
robert-kovacsics-part-ii-dissertation
DEVCON1 - BooJs
Eloquent JavaScript Book for Beginners to Learn Javascript
EloquenFundamentalsof Web Developmentt_JavaScript.pdf
Scala - from "Hello, World" to "Heroku Scale"
Reason - introduction to language and its ecosystem | Łukasz Strączyński
LISP: How I Learned To Stop Worrying And Love Parantheses
Programming Languages: some news for the last N years
The Scala Programming Language
(eBook PDF) Starting Out with C++: From Control Structures through Objects 8t...
The Rust Programming Language: an Overview
(eBook PDF) Starting Out with C++: From Control Structures through Objects 8t...
MozillaPH Rust Hack & Learn Session 2
Starting Out with C++: Early Objects 9th Edition by Tony Gaddis (eBook PDF)
scalaliftoff2009.pdf
Ad

Recently uploaded (20)

PDF
Insiders guide to clinical Medicine.pdf
PPTX
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PPTX
Week 4 Term 3 Study Techniques revisited.pptx
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
Classroom Observation Tools for Teachers
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PPTX
Institutional Correction lecture only . . .
PPTX
PPH.pptx obstetrics and gynecology in nursing
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
Pre independence Education in Inndia.pdf
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PPTX
master seminar digital applications in india
PDF
TR - Agricultural Crops Production NC III.pdf
PPTX
Pharma ospi slides which help in ospi learning
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PDF
RMMM.pdf make it easy to upload and study
Insiders guide to clinical Medicine.pdf
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
Renaissance Architecture: A Journey from Faith to Humanism
Week 4 Term 3 Study Techniques revisited.pptx
human mycosis Human fungal infections are called human mycosis..pptx
Classroom Observation Tools for Teachers
Microbial diseases, their pathogenesis and prophylaxis
Institutional Correction lecture only . . .
PPH.pptx obstetrics and gynecology in nursing
Module 4: Burden of Disease Tutorial Slides S2 2025
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
Supply Chain Operations Speaking Notes -ICLT Program
Pre independence Education in Inndia.pdf
Abdominal Access Techniques with Prof. Dr. R K Mishra
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
master seminar digital applications in india
TR - Agricultural Crops Production NC III.pdf
Pharma ospi slides which help in ospi learning
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
RMMM.pdf make it easy to upload and study
Ad

The Rust Programming Language 2nd Edition Second Converted Steve Klabnik Carol Nichols

  • 1. The Rust Programming Language 2nd Edition Second Converted Steve Klabnik Carol Nichols download https://ebookbell.com/product/the-rust-programming-language-2nd- edition-second-converted-steve-klabnik-carol-nichols-49465120 Explore and download more ebooks at ebookbell.com
  • 2. Here are some recommended products that we believe you will be interested in. You can click the link to download. The Rust Programming Language Covers Rust 2018 Illustrated Steve Klabnik https://ebookbell.com/product/the-rust-programming-language-covers- rust-2018-illustrated-steve-klabnik-50194554 The Rust Programming Language Steve Klabnik Carol Nichols https://ebookbell.com/product/the-rust-programming-language-steve- klabnik-carol-nichols-36194546 The Rust Programming Language Covers Rust 2018 Steve Klabnik Carol Nichols https://ebookbell.com/product/the-rust-programming-language-covers- rust-2018-steve-klabnik-carol-nichols-49850560 The Rust Programming Language Second Edition 2 Converted Steve Klabnik https://ebookbell.com/product/the-rust-programming-language-second- edition-2-converted-steve-klabnik-48000090
  • 3. The Rust Programming Language 1st Edition The Rust Project Developpers https://ebookbell.com/product/the-rust-programming-language-1st- edition-the-rust-project-developpers-23358024 The Rust Programming Language Steve Klabnik Carol Nichols https://ebookbell.com/product/the-rust-programming-language-steve- klabnik-carol-nichols-27553790 The Rust Programming Language Steve Klabnik Steve Carol Nichols https://ebookbell.com/product/the-rust-programming-language-steve- klabnik-steve-carol-nichols-36194548 The Rust Programming Language Covers Rust 2018 Carol Nichols https://ebookbell.com/product/the-rust-programming-language-covers- rust-2018-carol-nichols-37721398 The Rust Programming Language Steve Klabnik Carol Nichols https://ebookbell.com/product/the-rust-programming-language-steve- klabnik-carol-nichols-42174614
  • 6. CONTENTS IN DETAIL TITLE PAGE COPYRIGHT ABOUT THE AUTHORS FOREWORD PREFACE ACKNOWLEDGMENTS INTRODUCTION Who Rust Is For Teams of Developers Students Companies Open Source Developers People Who Value Speed and Stability Who This Book Is For How to Use This Book Resources and How to Contribute to This Book CHAPTER 1: GETTING STARTED Installation Installing rustup on Linux or macOS
  • 7. Installing rustup on Windows Troubleshooting Updating and Uninstalling Local Documentation Hello, World! Creating a Project Directory Writing and Running a Rust Program Anatomy of a Rust Program Compiling and Running Are Separate Steps Hello, Cargo! Creating a Project with Cargo Building and Running a Cargo Project Building for Release Cargo as Convention Summary CHAPTER 2: PROGRAMMING A GUESSING GAME Setting Up a New Project Processing a Guess Storing Values with Variables Receiving User Input Handling Potential Failure with Result Printing Values with println! Placeholders Testing the First Part Generating a Secret Number Using a Crate to Get More Functionality Generating a Random Number Comparing the Guess to the Secret Number
  • 8. Allowing Multiple Guesses with Looping Quitting After a Correct Guess Handling Invalid Input Summary CHAPTER 3: COMMON PROGRAMMING CONCEPTS Variables and Mutability Constants Shadowing Data Types Scalar Types Compound Types Functions Parameters Statements and Expressions Functions with Return Values Comments Control Flow if Expressions Repetition with Loops Summary CHAPTER 4: UNDERSTANDING OWNERSHIP What Is Ownership? Ownership Rules Variable Scope The String Type Memory and Allocation Ownership and Functions
  • 9. Return Values and Scope References and Borrowing Mutable References Dangling References The Rules of References The Slice Type String Slices Other Slices Summary CHAPTER 5: USING STRUCTS TO STRUCTURE RELATED DATA Defining and Instantiating Structs Using the Field Init Shorthand Creating Instances from Other Instances with Struct Update Syntax Using Tuple Structs Without Named Fields to Create Different Types Unit-Like Structs Without Any Fields An Example Program Using Structs Refactoring with Tuples Refactoring with Structs: Adding More Meaning Adding Useful Functionality with Derived Traits Method Syntax Defining Methods Methods with More Parameters Associated Functions Multiple impl Blocks Summary CHAPTER 6: ENUMS AND PATTERN MATCHING Defining an Enum
  • 10. Enum Values The Option Enum and Its Advantages Over Null Values The match Control Flow Construct Patterns That Bind to Values Matching with Option<T> Matches Are Exhaustive Catch-All Patterns and the _ Placeholder Concise Control Flow with if let Summary CHAPTER 7: MANAGING GROWING PROJECTS WITH PACKAG ES, CRATES, AND MODULES Packages and Crates Defining Modules to Control Scope and Privacy Paths for Referring to an Item in the Module Tree Exposing Paths with the pub Keyword Starting Relative Paths with super Making Structs and Enums Public Bringing Paths into Scope with the use Keyword Creating Idiomatic use Paths Providing New Names with the as Keyword Re-exporting Names with pub use Using External Packages Using Nested Paths to Clean Up Large use Lists The Glob Operator Separating Modules into Different Files Summary CHAPTER 8: COMMON COLLECTIONS
  • 11. Storing Lists of Values with Vectors Creating a New Vector Updating a Vector Reading Elements of Vectors Iterating Over the Values in a Vector Using an Enum to Store Multiple Types Dropping a Vector Drops Its Elements Storing UTF-8 Encoded Text with Strings What Is a String? Creating a New String Updating a String Indexing into Strings Slicing Strings Methods for Iterating Over Strings Strings Are Not So Simple Storing Keys with Associated Values in Hash Maps Creating a New Hash Map Accessing Values in a Hash Map Hash Maps and Ownership Updating a Hash Map Hashing Functions Summary CHAPTER 9: ERROR HANDLING Unrecoverable Errors with panic! Recoverable Errors with Result Matching on Different Errors Propagating Errors To panic! or Not to panic!
  • 12. Examples, Prototype Code, and Tests Cases in Which You Have More Information Than the Compiler Guidelines for Error Handling Creating Custom Types for Validation Summary CHAPTER 10: GENERIC TYPES, TRAITS, AND LIFETIMES Removing Duplication by Extracting a Function Generic Data Types In Function Definitions In Struct Definitions In Enum Definitions In Method Definitions Performance of Code Using Generics Traits: Defining Shared Behavior Defining a Trait Implementing a Trait on a Type Default Implementations Traits as Parameters Returning Types That Implement Traits Using Trait Bounds to Conditionally Implement Methods Validating References with Lifetimes Preventing Dangling References with Lifetimes The Borrow Checker Generic Lifetimes in Functions Lifetime Annotation Syntax Lifetime Annotations in Function Signatures Thinking in Terms of Lifetimes Lifetime Annotations in Struct Definitions
  • 13. Lifetime Elision Lifetime Annotations in Method Definitions The Static Lifetime Generic Type Parameters, Trait Bounds, and Lifetimes Together Summary CHAPTER 11: WRITING AUTOMATED TESTS How to Write Tests The Anatomy of a Test Function Checking Results with the assert! Macro Testing Equality with the assert_eq! and assert_ne! Macros Adding Custom Failure Messages Checking for Panics with should_panic Using Result<T, E> in Tests Controlling How Tests Are Run Running Tests in Parallel or Consecutively Showing Function Output Running a Subset of Tests by Name Ignoring Some Tests Unless Specifically Requested Test Organization Unit Tests Integration Tests Summary CHAPTER 12: AN I/O PROJECT: BUILDING A COMMAND LINE P ROGRAM Accepting Command Line Arguments Reading the Argument Values Saving the Argument Values in Variables
  • 14. Reading a File Refactoring to Improve Modularity and Error Handling Separation of Concerns for Binary Projects Fixing the Error Handling Extracting Logic from main Splitting Code into a Library Crate Developing the Library’s Functionality with Test-Driven Development Writing a Failing Test Writing Code to Pass the Test Working with Environment Variables Writing a Failing Test for the Case-Insensitive Search Function Implementing the search_case_insensitive Function Writing Error Messages to Standard Error Instead of Standard Outpu t Checking Where Errors Are Written Printing Errors to Standard Error Summary CHAPTER 13: FUNCTIONAL LANGUAGE FEATURES: ITERATO RS AND CLOSURES Closures: Anonymous Functions That Capture Their Environment Capturing the Environment with Closures Closure Type Inference and Annotation Capturing References or Moving Ownership Moving Captured Values Out of Closures and the Fn Traits Processing a Series of Items with Iterators The Iterator Trait and the next Method Methods That Consume the Iterator Methods That Produce Other Iterators
  • 15. Using Closures That Capture Their Environment Improving Our I/O Project Removing a clone Using an Iterator Making Code Clearer with Iterator Adapters Choosing Between Loops and Iterators Comparing Performance: Loops vs. Iterators Summary CHAPTER 14: MORE ABOUT CARGO AND CRATES.IO Customizing Builds with Release Profiles Publishing a Crate to Crates.io Making Useful Documentation Comments Exporting a Convenient Public API with pub use Setting Up a Crates.io Account Adding Metadata to a New Crate Publishing to Crates.io Publishing a New Version of an Existing Crate Deprecating Versions from Crates.io with cargo yank Cargo Workspaces Creating a Workspace Creating the Second Package in the Workspace Installing Binaries with cargo install Extending Cargo with Custom Commands Summary CHAPTER 15: SMART POINTERS Using Box<T> to Point to Data on the Heap Using Box<T> to Store Data on the Heap Enabling Recursive Types with Boxes
  • 16. Treating Smart Pointers Like Regular References with Deref Following the Pointer to the Value Using Box<T> Like a Reference Defining Our Own Smart Pointer Implementing the Deref Trait Implicit Deref Coercions with Functions and Methods How Deref Coercion Interacts with Mutability Running Code on Cleanup with the Drop Trait Rc<T>, the Reference Counted Smart Pointer Using Rc<T> to Share Data Cloning an Rc<T> Increases the Reference Count RefCell<T> and the Interior Mutability Pattern Enforcing Borrowing Rules at Runtime with RefCell<T> Interior Mutability: A Mutable Borrow to an Immutable Value Allowing Multiple Owners of Mutable Data with Rc<T> and RefCell< T> Reference Cycles Can Leak Memory Creating a Reference Cycle Preventing Reference Cycles Using Weak<T> Summary CHAPTER 16: FEARLESS CONCURRENCY Using Threads to Run Code Simultaneously Creating a New Thread with spawn Waiting for All Threads to Finish Using join Handles Using move Closures with Threads Using Message Passing to Transfer Data Between Threads Channels and Ownership Transference
  • 17. Sending Multiple Values and Seeing the Receiver Waiting Creating Multiple Producers by Cloning the Transmitter Shared-State Concurrency Using Mutexes to Allow Access to Data from One Thread at a Time Similarities Between RefCell<T>/Rc<T> and Mutex<T>/Arc<T> Extensible Concurrency with the Send and Sync Traits Allowing Transference of Ownership Between Threads with Send Allowing Access from Multiple Threads with Sync Implementing Send and Sync Manually Is Unsafe Summary CHAPTER 17: OBJECT-ORIENTED PROGRAMMING FEATURES Characteristics of Object-Oriented Languages Objects Contain Data and Behavior Encapsulation That Hides Implementation Details Inheritance as a Type System and as Code Sharing Using Trait Objects That Allow for Values of Different Types Defining a Trait for Common Behavior Implementing the Trait Trait Objects Perform Dynamic Dispatch Implementing an Object-Oriented Design Pattern Defining Post and Creating a New Instance in the Draft State Storing the Text of the Post Content Ensuring the Content of a Draft Post Is Empty Requesting a Review Changes the Post’s State Adding approve to Change the Behavior of content Trade-offs of the State Pattern Summary
  • 18. CHAPTER 18: PATTERNS AND MATCHING All the Places Patterns Can Be Used match Arms Conditional if let Expressions while let Conditional Loops for Loops let Statements Function Parameters Refutability: Whether a Pattern Might Fail to Match Pattern Syntax Matching Literals Matching Named Variables Multiple Patterns Matching Ranges of Values with ..= Destructuring to Break Apart Values Ignoring Values in a Pattern Extra Conditionals with Match Guards @ Bindings Summary CHAPTER 19: ADVANCED FEATURES Unsafe Rust Unsafe Superpowers Dereferencing a Raw Pointer Calling an Unsafe Function or Method Accessing or Modifying a Mutable Static Variable Implementing an Unsafe Trait Accessing Fields of a Union When to Use Unsafe Code
  • 19. Advanced Traits Associated Types Default Generic Type Parameters and Operator Overloading Disambiguating Between Methods with the Same Name Using Supertraits Using the Newtype Pattern to Implement External Traits Advanced Types Using the Newtype Pattern for Type Safety and Abstraction Creating Type Synonyms with Type Aliases The Never Type That Never Returns Dynamically Sized Types and the Sized Trait Advanced Functions and Closures Function Pointers Returning Closures Macros The Difference Between Macros and Functions Declarative Macros with macro_rules! for General Metaprogramming Procedural Macros for Generating Code from Attributes How to Write a Custom derive Macro Attribute-Like Macros Function-Like Macros Summary CHAPTER 20: FINAL PROJECT: BUILDING A MULTITHREADED WEB SERVER Building a Single-Threaded Web Server Listening to the TCP Connection Reading the Request A Closer Look at an HTTP Request
  • 20. Writing a Response Returning Real HTML Validating the Request and Selectively Responding A Touch of Refactoring Turning Our Single-Threaded Server into a Multithreaded Server Simulating a Slow Request Improving Throughput with a Thread Pool Graceful Shutdown and Cleanup Implementing the Drop Trait on ThreadPool Signaling to the Threads to Stop Listening for Jobs Summary APPENDIX A: KEYWORDS Keywords Currently in Use Keywords Reserved for Future Use Raw Identifiers APPENDIX B: OPERATORS AND SYMBOLS Operators Non-operator Symbols APPENDIX C: DERIVABLE TRAITS Debug for Programmer Output PartialEq and Eq for Equality Comparisons PartialOrd and Ord for Ordering Comparisons Clone and Copy for Duplicating Values Hash for Mapping a Value to a Value of Fixed Size Default for Default Values APPENDIX D: USEFUL DEVELOPMENT TOOLS
  • 21. Automatic Formatting with rustfmt Fix Your Code with rustfix More Lints with Clippy IDE Integration Using rust-analyzer APPENDIX E: EDITIONS INDEX
  • 22. THE RUST PROGRAMMING LANGUAGE 2nd Edition by Steve Klabnik and Carol Nichols, with contributions from the Rust Community
  • 23. 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. Printed in the United States of America First printing 27 26 25 24 23 1 2 3 4 5 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 For information on distribution, bulk sales, corporate sales, or translations, please contact No Starch Press, Inc. directly at info@nostarch.com or: No Starch Press, Inc. 245 8th Street, San Francisco, CA 94103 phone: 1.415.863.9900 www.nostarch.com 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
  • 24. / 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 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.
  • 25. 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 contributor, 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 member 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.
  • 26. FOREWORD It wasn’t always so clear, but the Rust programming language is fundamentally 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 providing 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 having 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 mistakes 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,
  • 27. 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 programmer in general. So dive in, get ready to learn—and welcome to the Rust community! Nicholas Matsakis and Aaron Turon
  • 28. PREFACE 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 configure them to use Rust 2021 edition idioms. See “Installation” on page 1 for instructions on installing or updating Rust, and see Appendix E for information on editions. The 2021 edition of the Rust language includes a number of improvements 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!
  • 29. ACKNOWLEDGMENTS 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.
  • 30. 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 technical 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
  • 31. 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 programming world: Cargo, the included dependency manager and build tool, makes adding, 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 operating 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, especially those new to programming. Companies Hundreds of companies, large and small, use Rust in production for a variety of tasks, including command line tools, web services, DevOps tooling, embedded devices, audio and video analysis and transcoding, cryptocurrencies, bioinformatics, search engines, Internet of Things applications, machine learning, and even major parts of the Firefox web browser.
  • 32. Open Source Developers Rust is for people who want to build the Rust programming language, community, 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 endeavors 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 ergonomics. Give Rust a try and see if its choices work for you.
  • 33. Who This Book Is For This book assumes that you’ve written code in another programming language, 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 programming 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 programming, 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 your hands dirty right away, Chapter 2 is the place for that. Chapter 3 covers Rust features that are similar to those of other programming languages, and in Chapter 4 you’ll learn about Rust’s ownership system. If you’re a particularly meticulous learner who prefers to learn every detail before moving on to the next, you might want to skip Chapter 2 and go straight to Chapter 3, returning to Chapter 2 when you’d like to work on a project applying the details you’ve learned.
  • 34. Chapter 5 discusses structs and methods, and Chapter 6 covers enums, match expressions, and the if let control flow construct. You’ll use structs and enums to make custom types in Rust. In Chapter 7, you’ll learn about Rust’s module system and about privacy rules for organizing your code and its public application programming interface (API). Chapter 8 discusses some common collection data structures that the standard library provides, such as vectors, strings, and hash maps. Chapter 9 explores Rust’s error- handling philosophy and techniques. Chapter 10 digs into generics, traits, and lifetimes, which give you the power to define code that applies to multiple types. Chapter 11 is all about testing, which even with Rust’s safety guarantees is necessary to ensure your program’s logic is correct. In Chapter 12, we’ll build our own implementation of a subset of functionality from the grep command line tool that searches for text within files. For this, we’ll use many of the concepts we discussed in the previous chapters. Chapter 13 explores closures and iterators: features of Rust that come from functional programming languages. In Chapter 14, we’ll examine Cargo in more depth and talk about best practices for sharing your libraries with others. Chapter 15 discusses smart pointers that the standard library provides and the traits that enable their functionality. In Chapter 16, we’ll walk through different models of concurrent programming and talk about how Rust helps you program in multiple threads fearlessly. Chapter 17 looks at how Rust idioms compare to object-oriented programming principles you might be familiar with. Chapter 18 is a reference on patterns and pattern matching, which are powerful ways of expressing ideas throughout Rust programs. Chapter 19 contains a smorgasbord of advanced topics of interest, including unsafe Rust, macros, and more about lifetimes, traits, types, functions, and closures. In Chapter 20, we’ll complete a project in which we’ll implement a low-level multithreaded web server!
  • 35. Finally, some appendixes contain useful information about the language in a more reference-like format. Appendix A covers Rust’s keywords, Appendix B covers Rust’s operators and symbols, Appendix C covers derivable traits provided by the standard library, Appendix D covers some useful development tools, and Appendix E explains Rust editions. There is no wrong way to read this book: if you want to skip ahead, go for it! You might have to jump back to earlier chapters if you experience any confusion. But do whatever works for you. An important part of the process of learning Rust is learning how to read the error messages the compiler displays: these will guide you toward working code. As such, we’ll provide many examples that don’t compile along with the error message the compiler will show you in each situation. Know that if you enter and run a random example, it may not compile! Make sure you read the surrounding text to see whether the example you’re trying to run is meant to error. In most situations, we’ll lead you to the correct version of any code that doesn’t compile. Resources and How to Contribute to This Book This book is open source. If you find an error, please don’t hesitate to file an issue or send a pull request on GitHub at https://github.co m/rust-lang/book. Please see CONTRIBUTING.md at https://github.c om/rust-lang/book/blob/main/CONTRIBUTING.md for more details. The source code for the examples in this book, errata, and other information are available at https://nostarch.com/rust-programming-l anguage-2nd-edition.
  • 36. 1 GETTING STARTED Let’s start your Rust journey! There’s a lot to learn, but every journey starts somewhere. In this chapter, we’ll discuss: Installing Rust on Linux, macOS, and Windows Writing a program that prints Hello, world! Using cargo, Rust’s package manager and build system Installation The first step is to install Rust. We’ll download Rust through rustup, a command line tool for managing Rust versions and associated tools. You’ll need an internet connection for the download. NOTE If you prefer not to use rustup for some reason, please see the Other Rust Installation Methods page at https://forge.rust-l ang.org/infra/other-installation-methods.xhtml for more options. The following steps install the latest stable version of the Rust compiler. Rust’s stability guarantees ensure that all the examples in
  • 37. the book that compile will continue to compile with newer Rust versions. The output might differ slightly between versions because Rust often improves error messages and warnings. In other words, any newer, stable version of Rust you install using these steps should work as expected with the content of this book. COMMAND LINE NOTATION In this chapter and throughout the book, we’ll show some commands used in the terminal. Lines that you should enter in a terminal all start with $. You don’t need to type the $ character; it’s the command line prompt shown to indicate the start of each command. Lines that don’t start with $ typically show the output of the previous command. Additionally, PowerShell-specific examples will use > rather than $. Installing rustup on Linux or macOS If you’re using Linux or macOS, open a terminal and enter the following command: $ curl --proto '=https' --tlsv1.3 https://sh.rustup.rs -sSf | sh The command downloads a script and starts the installation of the rustup tool, which installs the latest stable version of Rust. You might be prompted for your password. If the install is successful, the following line will appear: Rust is installed now. Great! You will also need a linker, which is a program that Rust uses to join its compiled outputs into one file. It is likely you already have one. If you get linker errors, you should install a C compiler, which will typically include a linker. A C compiler is also useful because some common Rust packages depend on C code and will need a C compiler.
  • 38. On macOS, you can get a C compiler by running: $ xcode-select --install Linux users should generally install GCC or Clang, according to their distribution’s documentation. For example, if you use Ubuntu, you can install the build-essential package. Installing rustup on Windows On Windows, go to https://www.rust-lang.org/tools/install and follow the instructions for installing Rust. At some point in the installation, you’ll receive a message explaining that you’ll also need the MSVC build tools for Visual Studio 2013 or later. To acquire the build tools, you’ll need to install Visual Studio 2022 from https://visualstudio.microsoft.com/downloads. When asked which workloads to install, include: “Desktop Development with C++” The Windows 10 or 11 SDK The English language pack component, along with any other language pack of your choosing The rest of this book uses commands that work in both cmd.exe and PowerShell. If there are specific differences, we’ll explain which to use. Troubleshooting To check whether you have Rust installed correctly, open a shell and enter this line: $ rustc --version You should see the version number, commit hash, and commit date for the latest stable version that has been released, in the following format:
  • 39. rustc x.y.z (abcabcabc yyyy-mm-dd) If you see this information, you have installed Rust successfully! If you don’t see this information, check that Rust is in your %PATH% system variable as follows. In Windows CMD, use: > echo %PATH% In PowerShell, use: > echo $env:Path In Linux and macOS, use: $ echo $PATH If that’s all correct and Rust still isn’t working, there are a number of places you can get help. Find out how to get in touch with other Rustaceans (a silly nickname we call ourselves) on the community page at https://www.rust-lang.org/community. Updating and Uninstalling Once Rust is installed via rustup, updating to a newly released version is easy. From your shell, run the following update script: $ rustup update To uninstall Rust and rustup, run the following uninstall script from your shell: $ rustup self uninstall Local Documentation
  • 40. The installation of Rust also includes a local copy of the documentation so that you can read it offline. Run rustup doc to open the local documentation in your browser. Any time a type or function is provided by the standard library and you’re not sure what it does or how to use it, use the application programming interface (API) documentation to find out! Hello, World! Now that you’ve installed Rust, it’s time to write your first Rust program. It’s traditional when learning a new language to write a little program that prints the text Hello, world! to the screen, so we’ll do the same here! NOTE This book assumes basic familiarity with the command line. Rust makes no specific demands about your editing or tooling or where your code lives, so if you prefer to use an integrated development environment (IDE) instead of the command line, feel free to use your favorite IDE. Many IDEs now have some degree of Rust support; check the IDE’s documentation for details. The Rust team has been focusing on enabling great IDE support via rust-analyzer. See Appendix D for more details. Creating a Project Directory You’ll start by making a directory to store your Rust code. It doesn’t matter to Rust where your code lives, but for the exercises and projects in this book, we suggest making a projects directory in your home directory and keeping all your projects there. Open a terminal and enter the following commands to make a projects directory and a directory for the “Hello, world!” project within the projects directory.
  • 41. For Linux, macOS, and PowerShell on Windows, enter this: $ mkdir ~/projects $ cd ~/projects $ mkdir hello_world $ cd hello_world For Windows CMD, enter this: > mkdir "%USERPROFILE%projects" > cd /d "%USERPROFILE%projects" > mkdir hello_world > cd hello_world Writing and Running a Rust Program Next, make a new source file and call it main.rs. Rust files always end with the .rs extension. If you’re using more than one word in your filename, the convention is to use an underscore to separate them. For example, use hello_world.rs rather than helloworld.rs. Now open the main.rs file you just created and enter the code in Li sting 1-1. main.rs fn main() { println!("Hello, world!"); } Listing 1-1: A program that prints Hello, world! Save the file and go back to your terminal window in the ~/projects/hello_world directory. On Linux or macOS, enter the following commands to compile and run the file: $ rustc main.rs $ ./main Hello, world! On Windows, enter the command .main.exe instead of ./main:
  • 42. > rustc main.rs > .main.exe Hello, world! Regardless of your operating system, the string Hello, world! should print to the terminal. If you don’t see this output, refer back to “Troubleshooting” on page 3 for ways to get help. If Hello, world! did print, congratulations! You’ve officially written a Rust program. That makes you a Rust programmer—welcome! Anatomy of a Rust Program Let’s review this “Hello, world!” program in detail. Here’s the first piece of the puzzle: fn main() { } These lines define a function named main. The main function is special: it is always the first code that runs in every executable Rust program. Here, the first line declares a function named main that has no parameters and returns nothing. If there were parameters, they would go inside the parentheses (). The function body is wrapped in {}. Rust requires curly brackets around all function bodies. It’s good style to place the opening curly bracket on the same line as the function declaration, adding one space in between.
  • 43. NOTE If you want to stick to a standard style across Rust projects, you can use an automatic formatter tool called rustfmt to format your code in a particular style (more on rustfmt in Appendix D). The Rust team has included this tool with the standard Rust distribution, as rustc is, so it should already be installed on your computer! The body of the main function holds the following code: println!("Hello, world!"); This line does all the work in this little program: it prints text to the screen. There are four important details to notice here. First, Rust style is to indent with four spaces, not a tab. Second, println! calls a Rust macro. If it had called a function instead, it would be entered as println (without the !). We’ll discuss Rust macros in more detail in Chapter 19. For now, you just need to know that using a ! means that you’re calling a macro instead of a normal function and that macros don’t always follow the same rules as functions. Third, you see the "Hello, world!" string. We pass this string as an argument to println!, and the string is printed to the screen. Fourth, we end the line with a semicolon (;), which indicates that this expression is over and the next one is ready to begin. Most lines of Rust code end with a semicolon. Compiling and Running Are Separate Steps You’ve just run a newly created program, so let’s examine each step in the process. Before running a Rust program, you must compile it using the Rust compiler by entering the rustc command and passing it the name of
  • 44. your source file, like this: $ rustc main.rs If you have a C or C++ background, you’ll notice that this is similar to gcc or clang. After compiling successfully, Rust outputs a binary executable. On Linux, macOS, and PowerShell on Windows, you can see the executable by entering the ls command in your shell: $ ls main main.rs On Linux and macOS, you’ll see two files. With PowerShell on Windows, you’ll see the same three files that you would see using CMD. With CMD on Windows, you would enter the following: > dir /B %= the /B option says to only show the file names =% main.exe main.pdb main.rs This shows the source code file with the .rs extension, the executable file (main.exe on Windows, but main on all other platforms), and, when using Windows, a file containing debugging information with the .pdb extension. From here, you run the main or main.exe file, like this: $ ./main # or .main.exe on Windows If your main.rs is your “Hello, world!” program, this line prints Hello, world! to your terminal. If you’re more familiar with a dynamic language, such as Ruby, Python, or JavaScript, you might not be used to compiling and running a program as separate steps. Rust is an ahead-of-time compiled language, meaning you can compile a program and give the executable to someone else, and they can run it even without having Rust installed. If you give someone a .rb, .py, or .js file, they
  • 45. need to have a Ruby, Python, or JavaScript implementation installed (respectively). But in those languages, you only need one command to compile and run your program. Everything is a trade-off in language design. Just compiling with rustc is fine for simple programs, but as your project grows, you’ll want to manage all the options and make it easy to share your code. Next, we’ll introduce you to the Cargo tool, which will help you write real-world Rust programs. Hello, Cargo! Cargo is Rust’s build system and package manager. Most Rustaceans use this tool to manage their Rust projects because Cargo handles a lot of tasks for you, such as building your code, downloading the libraries your code depends on, and building those libraries. (We call the libraries that your code needs dependencies.) The simplest Rust programs, like the one we’ve written so far, don’t have any dependencies. If we had built the “Hello, world!” project with Cargo, it would only use the part of Cargo that handles building your code. As you write more complex Rust programs, you’ll add dependencies, and if you start a project using Cargo, adding dependencies will be much easier to do. Because the vast majority of Rust projects use Cargo, the rest of this book assumes that you’re using Cargo too. Cargo comes installed with Rust if you used the official installers discussed in “Installation” on page 1. If you installed Rust through some other means, check whether Cargo is installed by entering the following in your terminal: $ cargo --version If you see a version number, you have it! If you see an error, such as command not found, look at the documentation for your method of installation to determine how to install Cargo separately.
  • 46. Creating a Project with Cargo Let’s create a new project using Cargo and look at how it differs from our original “Hello, world!” project. Navigate back to your projects directory (or wherever you decided to store your code). Then, on any operating system, run the following: $ cargo new hello_cargo $ cd hello_cargo The first command creates a new directory and project called hello_cargo. We’ve named our project hello_cargo, and Cargo creates its files in a directory of the same name. Go into the hello_cargo directory and list the files. You’ll see that Cargo has generated two files and one directory for us: a Cargo.toml file and a src directory with a main.rs file inside. It has also initialized a new Git repository along with a .gitignore file. Git files won’t be generated if you run cargo new within an existing Git repository; you can override this behavior by using cargo new --vcs=git. NOTE Git is a common version control system. You can change cargo new to use a different version control system or no version control system by using the --vcs flag. Run cargo new --help to see the available options. Open Cargo.toml in your text editor of choice. It should look similar to the code in Listing 1-2. Cargo.toml [package] name = "hello_cargo" version = "0.1.0" edition = "2021"
  • 47. # See more keys and their definitions at https://doc.rust-lan g.org/cargo/reference/manifest.xhtml [dependencies] Listing 1-2: Contents of Cargo.toml generated by cargo new This file is in the TOML (Tom’s Obvious, Minimal Language) format, which is Cargo’s configuration format. The first line, [package], is a section heading that indicates that the following statements are configuring a package. As we add more information to this file, we’ll add other sections. The next three lines set the configuration information Cargo needs to compile your program: the name, the version, and the edition of Rust to use. We’ll talk about the edition key in Appendix E. The last line, [dependencies], is the start of a section for you to list any of your project’s dependencies. In Rust, packages of code are referred to as crates. We won’t need any other crates for this project, but we will in the first project in Chapter 2, so we’ll use this dependencies section then. Now open src/main.rs and take a look: src/main.rs fn main() { println!("Hello, world!"); } Cargo has generated a “Hello, world!” program for you, just like the one we wrote in Listing 1-1! So far, the differences between our project and the project Cargo generated are that Cargo placed the code in the src directory and we have a Cargo.toml configuration file in the top directory. Cargo expects your source files to live inside the src directory. The top-level project directory is just for README files, license information, configuration files, and anything else not related to your
  • 48. code. Using Cargo helps you organize your projects. There’s a place for everything, and everything is in its place. If you started a project that doesn’t use Cargo, as we did with the “Hello, world!” project, you can convert it to a project that does use Cargo. Move the project code into the src directory and create an appropriate Cargo.toml file. Building and Running a Cargo Project Now let’s look at what’s different when we build and run the “Hello, world!” program with Cargo! From your hello_cargo directory, build your project by entering the following command: $ cargo build Compiling hello_cargo v0.1.0 (file:///projects/hello_carg o) Finished dev [unoptimized + debuginfo] target(s) in 2.85 secs This command creates an executable file in target/debug/hello_cargo (or targetdebughello_cargo.exe on Windows) rather than in your current directory. Because the default build is a debug build, Cargo puts the binary in a directory named debug. You can run the executable with this command: $ ./target/debug/hello_cargo # or .targetdebughello_cargo. exe on Windows Hello, world! If all goes well, Hello, world! should print to the terminal. Running cargo build for the first time also causes Cargo to create a new file at the top level: Cargo.lock. This file keeps track of the exact versions of dependencies in your project. This project doesn’t have dependencies, so the file is a bit sparse. You won’t ever need to change this file manually; Cargo manages its contents for you. We just built a project with cargo build and ran it with ./target/debug/hello_cargo, but we can also use cargo run to
  • 49. compile the code and then run the resultant executable all in one command: $ cargo run Finished dev [unoptimized + debuginfo] target(s) in 0.0 s ecs Running `target/debug/hello_cargo` Hello, world! Using cargo run is more convenient than having to remember to run cargo build and then use the whole path to the binary, so most developers use cargo run. Notice that this time we didn’t see output indicating that Cargo was compiling hello_cargo. Cargo figured out that the files hadn’t changed, so it didn’t rebuild but just ran the binary. If you had modified your source code, Cargo would have rebuilt the project before running it, and you would have seen this output: $ cargo run Compiling hello_cargo v0.1.0 (file:///projects/hello_carg o) Finished dev [unoptimized + debuginfo] target(s) in 0.33 secs Running `target/debug/hello_cargo` Hello, world! Cargo also provides a command called cargo check. This command quickly checks your code to make sure it compiles but doesn’t produce an executable: $ cargo check Checking hello_cargo v0.1.0 (file:///projects/hello_cargo) Finished dev [unoptimized + debuginfo] target(s) in 0.32 secs Why would you not want an executable? Often, cargo check is much faster than cargo build because it skips the step of producing an executable. If you’re continually checking your work while writing the code, using cargo check will speed up the process of letting you know if your project is still compiling! As such, many Rustaceans run
  • 50. cargo check periodically as they write their program to make sure it compiles. Then they run cargo build when they’re ready to use the executable. Let’s recap what we’ve learned so far about Cargo: We can create a project using cargo new. We can build a project using cargo build. We can build and run a project in one step using cargo run. We can build a project without producing a binary to check for errors using cargo check. Instead of saving the result of the build in the same directory as our code, Cargo stores it in the target/debug directory. An additional advantage of using Cargo is that the commands are the same no matter which operating system you’re working on. So, at this point, we’ll no longer provide specific instructions for Linux and macOS versus Windows. Building for Release When your project is finally ready for release, you can use cargo build --release to compile it with optimizations. This command will create an executable in target/release instead of target/debug. The optimizations make your Rust code run faster, but turning them on lengthens the time it takes for your program to compile. This is why there are two different profiles: one for development, when you want to rebuild quickly and often, and another for building the final program you’ll give to a user that won’t be rebuilt repeatedly and that will run as fast as possible. If you’re benchmarking your code’s running time, be sure to run cargo build --release and benchmark with the executable in target/release. Cargo as Convention With simple projects, Cargo doesn’t provide a lot of value over just using rustc, but it will prove its worth as your programs become
  • 51. more intricate. Once programs grow to multiple files or need a dependency, it’s much easier to let Cargo coordinate the build. Even though the hello_cargo project is simple, it now uses much of the real tooling you’ll use in the rest of your Rust career. In fact, to work on any existing projects, you can use the following commands to check out the code using Git, change to that project’s directory, and build: $ git clone example.org/someproject $ cd someproject $ cargo build For more information about Cargo, check out its documentation at https://doc.rust-lang.org/cargo. Summary You’re already off to a great start on your Rust journey! In this chapter, you’ve learned how to: Install the latest stable version of Rust using rustup Update to a newer Rust version Open locally installed documentation Write and run a “Hello, world!” program using rustc directly Create and run a new project using the conventions of Cargo This is a great time to build a more substantial program to get used to reading and writing Rust code. So, in Chapter 2, we’ll build a guessing game program. If you would rather start by learning how common programming concepts work in Rust, see Chapter 3 and then return to Chapter 2.
  • 52. 2 PROGRAMMING A GUESSING GAME Let’s jump into Rust by working through a hands-on project together! This chapter introduces you to a few common Rust concepts by showing you how to use them in a real program. You’ll learn about let, match, methods, associated functions, external crates, and more! In the following chapters, we’ll explore these ideas in more detail. In this chapter, you’ll just practice the fundamentals. We’ll implement a classic beginner programming problem: a guessing game. Here’s how it works: the program will generate a random integer between 1 and 100. It will then prompt the player to enter a guess. After a guess is entered, the program will indicate whether the guess is too low or too high. If the guess is correct, the game will print a congratulatory message and exit. Setting Up a New Project To set up a new project, go to the projects directory that you created in Chapter 1 and make a new project using Cargo, like so:
  • 53. $ cargo new guessing_game $ cd guessing_game The first command, cargo new, takes the name of the project (guessing_game) as the first argument. The second command changes to the new project’s directory. Look at the generated Cargo.toml file: Cargo.toml [package] name = "guessing_game" version = "0.1.0" edition = "2021" # See more keys and their definitions at https://doc.rust-lan g.org/cargo /reference/manifest.xhtml [dependencies] As you saw in Chapter 1, cargo new generates a “Hello, world!” program for you. Check out the src/main.rs file: src/main.rs fn main() { println!("Hello, world!"); } Now let’s compile this “Hello, world!” program and run it in the same step using the cargo run command: $ cargo run Compiling guessing_game v0.1.0 (file:///projects/guessing_ game) Finished dev [unoptimized + debuginfo] target(s) in 1.50s Running `target/debug/guessing_game` Hello, world! The run command comes in handy when you need to rapidly iterate on a project, as we’ll do in this game, quickly testing each
  • 54. iteration before moving on to the next one. Reopen the src/main.rs file. You’ll be writing all the code in this file. Processing a Guess The first part of the guessing game program will ask for user input, process that input, and check that the input is in the expected form. To start, we’ll allow the player to input a guess. Enter the code in Listi ng 2-1 into src/main.rs. src/main.rs use std::io; fn main() { println!("Guess the number!"); println!("Please input your guess."); let mut guess = String::new(); io::stdin() .read_line(&mut guess) .expect("Failed to read line"); println!("You guessed: {guess}"); } Listing 2-1: Code that gets a guess from the user and prints it This code contains a lot of information, so let’s go over it line by line. To obtain user input and then print the result as output, we need to bring the io input/output library into scope. The io library comes from the standard library, known as std: use std::io; By default, Rust has a set of items defined in the standard library that it brings into the scope of every program. This set is called the prelude, and you can see everything in it at https://doc.rust-lang.org/ std/prelude/index.xhtml.
  • 55. Random documents with unrelated content Scribd suggests to you:
  • 56. Stores of corn sold under price to the country labourers. The same plan was also adopted in the country. It was recommended by the Council, but it is not one of the fixed regulations enforced by them. In one case however we find that a small sum of money had been collected for a magazine of corn in Suffolk, and that now the Council ordered it to be used to supply the poor of Halesworth[441]. In many other cases corn was provided by the inhabitants themselves often by voluntary agreement made under the persuasion of the justices. In 1623 this method of helping the poor was usual in Hertfordshire. In March the Sheriff sends to the Council reports from the justices of the greater part of the country. He states that the justices and gentlemen have "by there good and charitable exsamples and perswasiones" provided a quantity of corn at nearly half the market price in "euery parish where neede requireth." There was enough to last until next harvest and they hope "noe complainte of the pore shall hereafter add any disturbance unto his Mati's most graciouse pittifull, and charitable minde[442]." In districts of Devonshire and Suffolk[443] also like plans were tried in 1623, while in 1631 similar methods of relief seem to have been universal in the counties of Essex and Norfolk, and to have been adopted in some districts in almost every eastern county. Thus in December 1630 in four of the hundreds of Essex arrangements were made for supplying the people with corn at home. The chief inhabitants "of theire owne accords" laid in a store for the poor allowing 7d., 18d. or 2s. the bushel and giving an equivalent amount in money to those that did not bake their own bread[444]. Next month we hear that this plan had been adopted in most of the shire; every parish had its store and the poor were served at 18d. and 2s. a bushel under the usual price. Sometimes when grain was scarce, bread and money were given instead. Our informant states that this provision of corn for the poor at cheap rates had had a considerable effect in lowering the price of grain[445]. From every hundred of Norfolk a report of the state of the corn supply of the poor was received, and some arrangement of this
  • 57. d. Other special methods of providing food for the poor. 2. Evidence as to success or failure of the corn regulations. kind is usually reported. In some hundreds two degrees of poverty were recognised. The very poor only paid half-a-crown a bushel for their barley, but "the labourers yt had nott so much neede" were served at three shillings[446]. This plan does not seem to have been general in Yorkshire, but it was adopted by at least eight hundreds[447]. There are moreover many examples of stores of this kind in Hertfordshire and some in every Eastern county except Northumberland and Lincolnshire[448]. The fact that special mention is made of poor labourers shows that relief was not confined to the disabled or to paupers. It was given in the eastern counties more than in the western probably because the scarcity was more felt in the east and the poor were in greater distress[449]. Sometimes other plans were adopted. The owners and dealers of corn were expected to contribute to the need of their less fortunate neighbours. At Reading the corn masters set apart a sack in every load to serve for the poor at twelvepence a bushel under the market rate[450]. It would seem that some allowance was usually made by dealers in corn, for another dealer who was a victim of a riot at Woodchurch states that out of ten quarters he left five to be sold to the poor[451]. Other expedients of this kind were adopted; in Devonshire the children of the poor were billetted on those able to give relief[452], and at Maidstone the town baked the bread and gave loaves to the day labourers and poorest inhabitants[453]. Three of the hundreds of Cambridgeshire tried a still more organised plan: "the poorer sort had weekly corne delivered to them at home at twelvepence in the bushell in the least under the market prices[454]." We have very varied opinions as to the success or failure of the organisation for supplying the poor with corn. The justices in several instances state that the search raised prices, and ask that a second search may not be made[455]. In a few cases they say the
  • 58. regulation of the markets was injurious. The most decided of these is an account from Edwinstree and Odsey, "And we humbly conceaue that or strickt lookeing to the marketts by or selves and others, very sufficient and diligent supervisors , whom we haue imploied wth a great deale of care in these businesses is an occacion that the marketts are the smaller, the corne dearer and new shifts and devises are found out[456]." In the autumn of 1631 inquiries as to the cause of the scarcity were instituted, and the Bridport authorities candidly replied that it was owing to the interference of the justices[457]. But perhaps the most interesting protest is that from Chipping Wycombe. It was a town on the borders of Buckinghamshire, which was largely inhabited by dealers in corn and was the market for the neighbouring parts of Oxfordshire and Berkshire. After the instructions of the Privy Council had been followed, only a quarter of the usual quantity was brought to the market. The dealers, the Mayor tells us, lost heavily because the price of meal had been fixed by the Lord Mayor, and both they and the farmers were disgusted at the lowering of prices in other parts of the country. Formerly the badgers had set aside sacks for the poor, and the farmers and others had provided stores for them. This they now refused to do, but the justices did their best and themselves sold to the poor under the market rates[458]. The dislike of the orders is very apparent in this report, but it bears witness to the fact that they were sometimes successful, since prices had been lowered in consequence in other parts of the country. But as Chipping Wycombe was inhabited largely by corn-dealers, and as it drew its supplies from other counties, the orders failed there, and the fact that Chipping Wycombe was such a town may have been not without its influence on the making of history, for John Hampden, we are told, was one of the justices present who witnessed the distress of this disastrous market-day. It was not a position in which he would judge favourably of the effects of governmental interference. Still the balance of evidence is in favour of the orders. When they were first put in force they seem to have had a considerable effect in
  • 59. lowering the price. Many of the reports sent in during the last half of December and beginning of January tell us that this was the case[459], though after the beginning of the year prices again rose, because the corn was wanted for seed as well as for food. However even as late as April 30th a report from the district of Horncastle in Lincolnshire informs us that the writers have ordered the markets to be furnished every week with a particular quantity, and that the price of oatmeal, which was the chief food of the poor in that part of the country, had been lowered from eight groats to one shilling and tenpence[460]. There are other statements of the same kind[461], but one of the most strongly expressed of these is from the justices of Suffolk, "We giue yr lo(rdshi)ps many humble thanks for your great fauours shewed unto vs and to the whole state of this county in these necessiteouse times by those most prudent, compassionate and charitable considerations deliuered in your bookes of directions and sent vnto vs wch we haue wth our uttermost endeauours laboured in euery parte to see accomplished as well by or selues as others. And we must acknowledge with or and the countryes great thankfulnesse unto yr lo(rdshi)ps that ye benefit wch hereof hath arisen hath bine beyonde all expectation inestemable and of wonderful effect[462]." But the strongest argument that on the whole these measures were beneficial is to be found in the fact that they were enforced throughout the country by the justices with very few protests. The justices would as a rule be landlords and generally corn owners; the regulations were against their interests, and, unless they had thought that they contributed to the public welfare, they would have complained more and performed less. When they thought a course objectionable they said so: many of them did not approve of a second search of the stocks of corn[463]; in several instances they said that the order to prevent millers from buying corn was not beneficial, because the millers sold in small quantities to the poor who did not come to market[464]. But the rest of the orders
  • 60. 3. Reasons for the adoption of the corn regulations. 4. Bearing of the scarcity measures concerning corn were enforced nearly always without comment or with approval. It is not difficult to see reasons for the success of such an organisation. Corn fluctuated violently in price because of the narrowness of the area from which the supplies came. Even with our own worldwide supply a corner in wheat has been attempted and for a time maintained. When little corn was imported into England, and even counties were largely self-supporting, farmers might easily raise the price by keeping back their corn from market[465]. But the great price was not always the worst of the trouble. The justices of Devonshire tell us that corn could not be had for money, and the statement is confirmed by Fitz-Geffrie in his Curse of Corne- horders, "O miserable condition! the poore man is put to a double labour, first to get a little money for Corne and then to get a little corne for money & this last is the hardest labour; he might haue earned almost halfe a bushell while hee runnes about begging to buy halfe a pecke[466]." We must remember the narrowness of the market; the excessive fluctuations in price, and the difficulty of finding a seller willing to sell a small quantity of grain, before we can criticise fairly the organisation which was established during these years of high-priced corn. In any case the corn orders of the Government seem to have helped to maintain the public peace. In 1527, in 1551, in 1587, in 1597, and in 1623 the rise in the price of corn immediately occasioned disorder[467], and even in 1630 attacks were made on the carts carrying corn, and there were other signs of disturbance[468]. But in this last season of scarcity there was no serious outburst. The orders of the Government probably relieved the distress and certainly helped to convince the people that their rulers were trying to help them.
  • 61. on the history of poor relief. a. The training of the justices. b. The standard of comfort of the poorer classes. The organisation for supplying the poor with corn in 1631 is both indirectly and directly connected with the history of poor relief. We have already seen that the orders for supplying corn seem to have suggested the orders for the ordinary relief of the poor, and that both sets of orders were worked by similar methods. The season of 1630-1 is the first in which the administrators seem to have properly fulfilled their duties. Then the commands of the Government seem to have been vigilantly enforced. This was not always easily accomplished, rebellious inhabitants were coerced, negligent justices were punished[469]. But on the whole the justices seem to have worked with zeal, and the success obtained by them during this exceptional crisis must have made it easier for them to cope with the relief of the poor in more ordinary times. Moreover the direct relief afforded by the corn stores must be taken into account when we attempt to estimate the amount of comfort enjoyed by the manual workers in the reign of Charles I. Prof. Rogers has compared the condition of the labouring population at different times by estimating the amount of food which could be bought by a labourer receiving average wages in each period. This method of comparison leads him to the conclusion that the majority of the population were in a very miserable condition before the outbreak of the Civil War[470]. But in 1630-1, and to some extent also in 1623, labourers did not pay the market price for their food, and this fact must modify any conclusion derived from such a source so far as the reigns of James I. and Charles I. are concerned. Not only was corn sold under price from public granaries and stores, but it is probable that whenever arrangements were made to serve the labourers at home the prices were somewhat reduced, as the sellers would then be saved the trouble of taking the corn to market, and the expense of paying the market tolls.
  • 62. 5. Provision of fuel for the poor in Winter. Moreover it has often been pointed out that the relative comfort of any class can be better ascertained if we consider the earnings of the family rather than those of the individual[471]. This was a period in which women could easily obtain work in spinning and when children were apprenticed at an early age, and so required little support from their parents. For these reasons it seems likely that the labourer of the reign of Charles I. would be better off than the amount of his wages would lead us to suppose, and this estimate is confirmed by the scale of diet fixed for the boys in the Children's Hospital of Norwich in 1632. The boys in the hospital were between the ages of ten and fourteen. For dinner they were always to have six ounces of bread and a pint of beer: three days in the week they had also a pint of pottage and six ounces of beef, and on the remaining four an ounce of butter and two of cheese. For supper they had always six ounces of bread, a pint of beer, an ounce of butter and two of cheese, and for breakfast every day three ounces of bread, half an ounce of butter and half a pint of beer[472]. As this represents the food of the destitute orphans of Norwich it is not likely to be much better than the usual standard of the poorest class, and seems to compare very favourably with the food of a boy in the same class in our own time. The ordinary standard of living thus does not appear to be miserable, but the poor must have suffered terribly, if there had been no exceptional relief, whenever there was no work for them to do, and when corn was double the usual price. It is these fluctuations that were the chief source of misery, and by lessening their effect the scarcity measures of the time were of enormous importance to the whole of the labouring class. But relief in times of emergency was afforded to the needy in other times of exceptional distress. In Winter fuel was provided. Thus at St Albans, wood was bought for the poor in the reign of Queen Elizabeth[473]. In London there was a coal yard before 1590, and early in the reign of James I. the City
  • 63. 6. Help in times of sickness and plague. authorities obtained permission to import four thousand chaldron of "sea cole" free of duty for the purpose of supplying those in need of help[474]. Payments for fuel formed part of the regular organisation at Norwich[475], and directions to secure a supply to the poor of their district are contained also in the orders to the overseers of 1623[476]. This provision is another illustration of the fact that a great deal of the relief given was designed to protect the people from excessive fluctuations in price. Methods of relieving the poor in times of sickness were also numerous. The Great Plague of London was not an isolated attack; throughout the seventeenth century few years pass without an outbreak in one of the large towns. Special orders were drawn up to prevent the spread of infection; watchmen were appointed to guard stricken houses, and the inmates for the time had to be supported by the community[477]. The cost of this severely taxed local resources. At Cambridge we hear that in 1630, 2800 claimed relief and only seven score were able to contribute. In this case a brief was issued authorising collections from other parts[478], and London and Norwich sent generous contributions[479]. One town seems to have helped another frequently when this scourge broke out: New Sarum sent aid to London, Norwich to Yarmouth, and both New Sarum and Bury thanked the Londoners for the help they had themselves received under like circumstances[480]. Pest houses were often established; at Reading eight were built, and we hear of their erection in Norwich, London, Cambridge and Windsor[481]. The way the funds were raised for the plague-stricken poor of Windsor is one of the many illustrations of the fact that private charity and public rates were often used for the same purposes and administered by the same officials. The site for the pest house was given by an alderman, some of the money was raised for the relief of the infected poor "by way of taxation," part was given by gentlemen of the neighbourhood, and the rest was probably paid out of the town chest[482]. At Hitchen and in other
  • 64. 7. Contributions to sufferers from fire. places relief was given to the plague-stricken by means of the poor law organisation[483]. The Privy Council frequently made orders connected with the plague. Sometimes they ordered the erection of pest houses, sometimes a special collection. In Grantham and Worcester the rich fled from the infected town, so that government was at a standstill; the absentees were required to pay double rates and, if necessary, to return and help govern the town[484]. At another time the paper-makers in Suffolk were prevented from working because of the plague, and a special collection was ordered for them[485]. All these orders illustrate the paternal nature of the Privy Council government, and also seem to show that in social matters it was exercised in favour of the poor. But not only in time of plague was provision made for the sick. At Norwich it was part of the regular organisation for the poor; in London St Thomas's and St Bartholomew's hospitals were already in existence, and in most towns there were numerous lazar houses. In some places the help provided was even greater than that of to-day; a town physician was appointed especially to look after the poor. Newcastle adopted this plan in the reign of Elizabeth, and the practice was continued down to the time of the Civil War, and in 1629 a "learned physician" was engaged by the Mayor and Corporation of Barnstaple to give advice gratis to the poor[486]. This happened just at the time when, as we have seen, there was great activity in matters connected with the poor, and is an illustration of the fact that the duties of the seventeenth century municipality were very various, and that even in 1629 the town authorities were sometimes pioneers in matters concerning the poor. Fire was another way in which sudden loss was caused to large numbers of people. Houses were still built largely of wood and often very close together. Whole towns were not infrequently destroyed. Tiverton suffered twice in this way, and the suddenness of the calamity to so flourishing a town seems to have especially struck men's
  • 65. 8. Characteristics of seventeenth century poor relief. a. Little distinction between paupers and non-paupers. imagination. "He which at one a clocke was worth fiue thousand pound and as the Prophet saith drunke his Wine in bowles of fine Siluer plate, had not by two a clocke so much as a woodden dish left to eate his meate in, nor a house to couer his sorrowfull head"[487]. In the second destruction of 1612 three hundred of the poor people were boarded in the shire, and collections to rebuild the town were made throughout the country. Similar disasters happened to several other towns, to Dorchester in 1613 and Hertford in 1637, and like collections were made for them among charitable people. 1632: "Paid Mr Henderson the townes physician his ½ yeares stipend due at lady-day 1632, 20l." A payment of £10 was also made in 1647, to "doctor Samuel Rand the townes physition." M. A. Richardson's Tracts, Vol. III. p. 47. Extracts from the municipal accounts of Newcastle. Barnstaple, Nov. 24th, 1629: "Dr Symes a learned Physician engaged by Mayor and Corporation to be resident in town and give advice gratis to the poor at £20 per annum for two years to be paid out of town stock if not raised by subscriptions." Wyot's Diary, Barnstaple Records, North Devon Herald, April 21, 1881. Relief was also given to individuals who suffered loss from fire, sometimes by means of authorised collections and sometimes out of the public funds[488]. Thus in the North Riding £20 was paid to twelve persons of Thornton and Farmanby, on account of their losses caused by fire[489]. Thus in the first half of the seventeenth century relief in times of emergency forms a considerable part of the assistance given to people in distress. That provided in years of high priced corn was not distributed only to those who were usually paupers but to the whole of the labouring class; that afforded in times of fire or sickness affected all classes of the community. There was thus much less difference between paupers and the rest of the community than there is to-day. All classes were relieved because poor relief was originally part of a paternal system
  • 66. b. Little distinction between relief afforded by voluntary donations and that provided by poor rates. of government under which the rulers regarded the maintenance of the usual prosperity of every class as a part of their duties. There is a curious case of landlord and farmer relief during the season of plenty in 1619. It was then stated that of late years there had been so much corn that the farmers were impoverished. A letter was therefore sent to the justices of every county ordering them to confer concerning some fit place where a magazine might be provided for storing a quantity of corn. The reason for this is stated to be that it is the "care of the state to provyd as well to keepe the price of corne in tymes of plenty at such reasonable rates as may afford encouragemt and lively good to the farmer and husbandman as to moderate the rates thereof in time of scarcitie for the releefe of the poorer folke"[490]. Few regulations could make it clearer than this, that the paternal measures of the Government were not confined to one particular class, but affected the whole of the community. The distinction between paupers and non-paupers therefore was much less clear than it is to-day, and it is also true that the distinction between voluntary contributions and compulsory poor rates was much less rigidly defined. The supply of the poor with corn is nearly always stated to have been a voluntary measure, but it was carried out under very considerable pressure from the justices. Sometimes the pressure amounted to compulsion. Thus in the Sarum division of Wiltshire some gave "franklie and freely good quantities of their store" to the poor but others were "wilfull." The justices "terrified them a little wth conventing them before the Lords of the Counsell and then they seemed very willing and tractable"[491]. It is difficult to say therefore how far the corn charities of the time were voluntary and how much they were compulsory. There was also a close connection between private and public charity in other forms of relief. Probably in every town there were numbers of endowed charities controlled by the municipal officers or by overseers or by some public or semi-public authorities, which were practically a part of the
  • 67. same system as that enforced by law. Such were the four royal hospitals of London and the hospitals of Gloucester and Norwich. Such also were the many almshouses under the management of corporations, as were the almshouses founded respectively by Leche and by Kendrick at Reading, and the many charities for apprenticing poor children and lending money to poor tradesmen, which we shall afterwards consider in detail. Sometimes the connection was closer still, and the workhouse like the Free Library of to-day might be partly provided by private generosity and partly by public rates. Such was the case with the Barnstaple workhouse and the Jersey school of Newark[492]. The relief of the poor in times of emergency thus brings into prominence two of the main features of the poor relief of the time. First, that the public compulsory system was developed from a voluntary system and that in the seventeenth century voluntary and public poor relief were closely connected. Secondly, that the poor relief of the time was intimately connected with the general system of government under which all classes were compelled by Government to do their duties and any class might be relieved that for the time failed to obtain its usual degree of prosperity.
  • 69. CHAPTER XI. METHODS OF RELIEF, 1597-1644 (continued). B. Ordinary Relief. α. Impotent poor. 1. Almshouses and endowed charities. (a) Old endowments which remained unchanged through the Reformation. (b) Old endowments regranted to the Corporation or other public body. (c) Fresh endowments. (d) Pensions and gifts from endowed charities. 2. Provision for the old from compulsory rates. (a) Relief from the county by pensions paid to soldiers and sailors and by hospitals maintained by county funds. (b) Relief from the parish by pensions paid to the destitute, by the grant of a house, or by arrangements for free board and lodging in the house of some parishioner. β. Children. 3. Provision for children by apprenticeship. (a) To masters. (b) To the masters of the Bridewells or industrial schools of the time.
  • 70. α. The impotent poor. 1. Almshouses and endowed charities. a. Old endowments which remained unchanged through the Reformation. 4. Schools for little children and orphanages. γ. Able-bodied poor. 5. Relief given to prisoners. 6. Provision of funds to provide work for the unemployed. 7. Methods of providing work. (a) Stocks used to employ the poor in their homes or elsewhere. (b) Introduction of new trades. (c) Workhouses and Jersey schools. (d) Bridewells. (e) Emigration. (f) Pressure on employers. (g) Advancement of capital without interest. We have seen how the poor were relieved in times of special emergency; we will now examine the kind of help that was bestowed upon those classes of poor who in almost every community were more or less constantly in need of assistance. We will notice first the relief given to the impotent and aged poor; secondly, the measures adopted to provide for destitute children; and lastly, the methods used to find work for the unemployed or to suppress vagrants. The method of relieving the impotent poor differed very considerably from that with which we are familiar. The workhouses of the seventeenth century were mainly places for people who could work, the aged and impotent poor were often relieved by almshouses controlled by public and by private authorities, but founded and maintained by private liberality. It was indeed an age in which almshouses or hospitals as they were often called abounded. Probably there were nearly as many in existence then as there are to-day, in spite of the fact that our population has
  • 71. 1 b. Old endowments regranted to the Corporation or other public body. increased sixfold. Some of these hospitals were old endowments that had survived the Reformation; others had been dissolved with the other religious houses and regranted to the municipal authorities of the place to which they belonged; many more were founded during the reigns of Elizabeth, James I., and Charles I. The well-known Hospital of St Cross at Winchester is a good example of an old foundation that has had a continuous existence from its first endowment in the middle ages until the present day. The modern tourist, like the wayfarer of mediæval times, may partake of the refreshment provided by its ancient regulations, and may still receive his bread and beer like a seventeenth century beggar. But it has also been an almshouse since the time of Henry II. By the Charter of Foundation "thirteen poor men, feeble and so reduced in strength, that they can scarcely, or not at all, support themselves without other aid, shall remain in the same hospital constantly; to whom necessary clothing, provided by the Prior of the Establishment, shall be given, and beds fit for their infirmities; and daily a good loaf of wheaten bread of the weight of five measures, three dishes at dinner and one for supper, and drink in sufficient quantity[493]." This hospital was not dissolved by Henry VIII. but continued under its old regulations throughout the Reformation. Laud ordered inquiries to be made concerning it shortly after 1627, and the thirteen pensioners were then maintained with full allowances[494]. Many hospitals survived the dissolution besides St Cross and remained in private hands; a few like St Giles's, Hereford, or St Bartholomew's at Sandwich had been governed by the town- rulers from the time of their foundation[495], and these for the most part retained their old endowments and remained under municipal management. Other hospitals were regranted to the Corporations of their respective cities and towns soon after the dissolution in the same way as St Bartholomew's had been given to the City of London. Such was the case with St Bartholomew's of Gloucester. Queen Elizabeth stipulated that some of the payments
  • 72. formerly made by the Crown should be remitted, but placed the rest of the revenues in the hands of the Corporation on condition that a physician and surgeon and forty poor people should be there maintained[496]. Two other of the ancient hospitals of Gloucester came into the hands of the Corporation. One of these, St Margaret's Hospital, provided for ten poor men in 1562, and was then governed by the town authorities; the other, St Mary Magdalen, was granted to the city both by Queen Elizabeth and King James, and was called King James's Hospital[497]. Even if a hospital came into private hands it often returned to its original purpose. Sentiment as to its rightful use was probably very strong in the case of any institution which had been founded to do a work which obviously needed doing. Thus Kineburgh's, another of the old hospitals of Gloucester, had been sold at the dissolution to a Mr Thomas Bell, and was afterwards refounded by him and placed under the care of the Corporation. His donation was confirmed by Queen Elizabeth, and during the reign of James several other small endowments were added by various donors for the maintenance of the poor there[498]. Gloucester was perhaps especially fortunate in retaining so many of its old endowments, but elsewhere similar arrangements were made. St Giles's of Norwich, St Leonard's of Launceston, St Edmund's of Gateshead, St Thomas's and St Catherine's of York, St Mary Magdalen's of King's Lynn, and Trinity Hospital of Bristol were all old foundations which, during the sixteenth and seventeenth centuries, came into the hands of the corporation of the town to which they severally belong[499]. St Giles's Hospital of Norwich may be taken as an example of these re-established hospitals. According to the Letters Patent of Edward VI. it was granted to the Mayor and Corporation of Norwich, and was to be called the House of God or the House of the Poor: forty men and four matrons were to be provided for; they were to receive bed and bed-clothes, bread, meat, drink and firing. The pensioners were not appointed for life, but were removable from week to week or from day to day[500]. This hospital therefore was very much like a modern workhouse, except that it was supported by endowments or by voluntary subscriptions.
  • 73. 1 c. Fresh endowments. Occasionally these ancient charities came to be managed by the vestry. Thus in Bristol there were three old endowments of this sort. Redcliffe almshouse was supposed to have been established about 1440 by the famous Bristol merchant William Canninge; the Temple Gate almshouse and Burton's were probably foundations of an even earlier date. The two former were governed by the vestry of St Mary, Redcliffe, and long before 1821 had become simply houses in which aged paupers were placed by the overseers[501]. Burton's almshouse was governed by the vestry of St Thomas's parish, and was used as an almshouse from which paupers were not excluded. These institutions had thus then become part of the compulsory and legal system of poor relief rather than of the voluntary charity which existed by its side. But not only were there many old foundations for helping the aged poor, but the century from 1550 to 1650 was itself the great time of the foundation of new almshouses. It is rare to find a town of any size in which some institutions of this kind were not established during these years, though in country parishes they were not so frequent. They were governed in many different ways, but generally by some public body or by some set of men closely connected with the authorities who were responsible for the administration of poor-relief. Some were governed by the Corporation like the small almshouse founded by Fox at Beverley. Many resembled the Temple Hospital at Bristol; this was endowed by Sir Thomas White and was vested in trustees who were members of the Corporation. A few were managed by merchant or craft companies associated with the government of the town; such was the case with the Merchants' Hospital of Bristol and Dame Owen's almshouses in Islington. Others were in the hands of private trustees sometimes connected with the founder's family, at other times with his position. The Archbishops of Canterbury were generally associated with some of the favourite charities of the time. Grindal provided a stock for setting the poor to work, Abbot a workhouse, Laud apprenticeship endowments, and Whitgift an almshouse at Croydon for twenty-eight poor people, the government
  • 74. 1 d. Pensions and gifts from endowed charities. of which he vested in his successors in the see of Canterbury. These hospitals were usually filled by the aged and impotent of the poorer classes. But occasionally they also supplied the wants of the poor in a better social position. The Charterhouse of Colonel Newcome fame was a foundation of the reign of King James, and supplied a refuge for eighty poor gentlemen, merchants, soldiers, or mariners. Altogether the almshouses of the time formed a very important part of the provision for the poor. In some towns like that of Hereford[502] they were extremely numerous. Other places like Morton Hampstead seem to have established a public almshouse for the poor, but as a rule these institutions were privately endowed, and the help given by them was thus free from the sting that is attached to legal and compulsory charity. But besides the almshouses many other charities were founded to help the aged poor, some of which have proved of doubtful benefit to their successors. Many pensions and gifts of small amount were distributed by public or semi-public bodies. The City Companies of London frequently received bequests of this kind. Thus the Clothworkers administer the gift of Sir Thomas Trevor. In 1622 he bequeathed £100 in order that six poor women might have 20s. a piece in quarterly instalments. At Bristol every week some one poor widow receives 10s. from Mr Whitson's charity, and two poor householders have 20s. each, though neither widow nor householder can have the gift more than once in the same year[503]. Innumerable smaller charities also exist in particular towns and parishes ordering the distribution of sixpences and shillings on particular Sundays or Feasts, or after the hearing of some sermon. Even more frequently bread charities were established. Thus in Hereford Cathedral twelve poor people receive a loaf every Saturday, and sixpence on twelve of the principal feasts and vigils of the year[504]. Sometimes so many poor men or women are "apparelled," or gowns, shirts and smocks are bought and distributed: more often fuel and wood are provided[505]. Bequests of this kind are very
  • 75. 2. Provision for the old from compulsory rates. 2 a. Relief provided by county funds. 2 b. Relief of the aged by means of pensions from the parish or by the provisions of houses numerous, but the amount of relief afforded to each individual is often ridiculously small. Still the value of money was three or four times greater then than it is to-day, and a pension of 10s. or 20s. was a much greater contribution towards the maintenance of the poor person. Moreover, parochial authorities and officials of City Companies had comparatively few people to deal with, and it was possible for them to know something about the recipients of these charitable doles. Altogether the number of endowed charities which afforded assistance to old people was large in the seventeenth century in comparison with the number of persons who were in need of relief. Moreover, new almshouses were continually founded throughout this period and until the close of the century. Probably many of these are in existence to-day, but there has been no increase at all proportionate to the growth of the population, while a few of the old institutions like the Redcliffe almshouse at Bristol have become part of the legal system of relief while others have disappeared altogether[506]. But although the aged poor were largely relieved by almshouses there were still many who were provided for by the legal and compulsory system. Some hospitals were supported by the county funds. There were several in the North Riding of Yorkshire which were used as almshouses for the impotent and aged poor and received grants from the County Treasurer[507]. Aged soldiers and sailors were also provided for not by the parish but by the county. As we should expect this was found to be a heavy charge in Devonshire, and the magistrates grumbled at the amount they had to give for this purpose[508]. More often the aged poor were relieved by the funds raised by the parish. Two methods seem to have been adopted. The most usual was what we should now call a system of out-relief. Pensions
  • 76. or free board and lodging. β. Children. 3 a. Apprenticeship to masters. were granted varying in amount from threepence to two shillings a week, but generally about one shilling[509]. Sometimes in addition rent was paid and often habitations were provided which were built by the overseers on the waste[510]. But the poor in these were not under any special control but were allowed to look after themselves in other respects. In some parishes, however, instead of receiving weekly pensions the poor were billeted on the rich. In a report from the district of Furness and Cartmell, one hundred and seventy-six people were relieved in this manner, and two hundred and eighty-eight by means of pensions. In this case each parish adopted one method or the other exclusively; thus in Alythwaite thirty-nine poor were billeted, in Coniston twelve were provided for by money payments[511]. In other cases the method of billeting existed as an exceptional practice side by side with the pension system. Thus in Staplegrove, Somerset, in 1599, after the list of payments given for the poor, there are the names of two men, each of whom kept a poor impotent person in his house[512]. The parochial system of the time was therefore mainly a system of out-relief and sometimes free lodging, but it was modified by a practice of "boarding out" the aged. It was of considerably less importance than it is to-day because the amount of endowed charities bore a much greater proportion to the number of old who were to be relieved. We will now consider the main methods of providing for the young. Compulsory education does not seem to be peculiar to the nineteenth century. In the reign of Charles I. all children had to be taught to work and trained to a trade. The method chiefly employed was that of apprenticeship. But schools, training homes and orphanages also existed in which children received the technical education of the time. Parents were obliged to apprentice their children or put them into service as soon as they were old enough. If the parents were able they paid the preliminary fee themselves; if not, the parish found masters for the children, but
  • 77. in this case they often had to work at the more unskilled trades. Sometimes money was paid for the pauper apprentice as for any other child, but at other times men were forced to keep the children without payment. There was often, as we should expect, a great deal of friction in the matter. In a report from Yorkshire, signed by Lord Fairfax, we are told that the justices do their best to find masters and keep the children with them, but that there was considerable difficulty in so doing[513]. Elsewhere there are also hints that the masters wished to free themselves from any burden of the kind[514], but there is much to make us think that on the whole the method at this time worked well. It was apparently the favourite remedy for the time for the evils of poverty. The writers of the legal handbooks insist that it was an especially important part of the duty of overseers[515], while throughout the seventeenth century numerous bequests for the purpose were left by private persons[516]. This is very strong evidence that the philanthropists of the time thought that the binding of poor children apprentice was an excellent way of providing for their maintenance and training. Laud himself was especially interested in the matter. In his own lifetime he made a gift for the purpose of apprenticing ten poor boys of Reading[517], and either during his lifetime or by his will he also provided funds for the same object in Croydon, Wokingham, Henley, Wallingford, and New Windsor[518]. Moreover the Privy Council appear to have specially enforced this part of the relief of the poor and to have demanded and received more detailed reports on this subject than on any other. This action of the Privy Council and the number of these bequests therefore make us believe that the evils of pauper apprenticeship were not very prominent in the seventeenth century. No doubt the fact that it was then the usual custom for an apprentice to board with his master and not a practice chiefly confined to children brought up by charity, made a great difference. Both kinds of apprentices were bound in the same way and would tend to be dealt with in the same manner. The selection of the master would make the principal difference; and the welfare of the apprentice would depend upon the care taken by the administrators
  • 78. 3 b. In the bridewells, or Industrial schools of the time. of the charities and the parochial funds in providing masters for the children. The picture in the Fortunes of Nigel of Jenkin Vincent, the London apprentice of this time brought up at Christ's Hospital, could not have been very unlike the reality. Great hardship must have been inflicted in some cases[519], but when the practice was new and the custom general, the apprentice bound by charitable funds would not usually be treated much worse than other apprentices. Otherwise it is not probable the Privy Councillors in their public capacity, and an Archbishop and many other charitable people in their private capacities, would have taken so much trouble to extend this practice by finding the funds for the purpose of thus providing for the maintenance and education of poor children. But not all destitute children were bound apprentice to masters in the town. The bridewells or workhouses of the time had often a special children's department which seems to correspond with our own Industrial schools. The London Bridewell had thus two distinct functions to perform. On the one side it was a House of Correction, on the other it was a technical school for young people. Sometimes the orphaned sons of freemen were received there, at other times children were sent by the overseers of the parishes, and often young vagrants were brought in from the London streets. They were trained in very various occupations: a full report of the hospital was drawn up in 1631, and we are then told that "four silk weavers keep poore children taken from the streets or otherwise distressed, to the number of forty-five." There were also more than a hundred others at that time in the Hospital who were apprenticed to pinmakers, ribbon weavers, hempdressers, linen weavers, and carpenters[520]. Christ's Hospital at Ipswich, the Hospital at Reading, and the Nottingham House of Correction, had all training departments of this kind in which many of the poor children of these towns were taught trades.
  • 79. 4. Schools for little children and orphanages. Besides all this, children who were too young to be apprenticed were in many places taught to spin and sometimes to read and write. We have seen that in Norwich in every parish "a select woman" was appointed for this purpose in the reign of Queen Elizabeth, and in 1630 a similar order was made to the effect "that a knittinge schooledame shalbe provided in every parishe where there is not one already, to sett children and other poore on worke[521]." Even in the hamlets like those of Whitwell and Sellside, in the county of Westmoreland, three poor boys were maintained at the school by the parish who were to be taught trades as soon as they were old enough[522]. In Hertfordshire we are told that many had been placed as apprentices "and such as are not of fitt yeares to bee put forth wee haue caused to bee sett to spinning and such smale worke as is most meete for them according to the tendernesse of their age that idlenesse may not fasten in them[523]." These schools were not improbably very numerous. In documents containing the instructions of justices to overseers knitting schools were advocated. Thus in directions issued in 1622 by some of the justices of Norfolk for the hundreds of Eynesford and South Erpingham, the justices resolve "that poore children be put to schoole to knittinge and spinninge dames and the churchwardens and ouerseers for the poore to paie the schoole dames their wages where the parents are not able[524]." All this points to a system of popular education of the kind then approved. In the largest towns orphanages also were established about this time. Christ's Hospital in London, as we have seen, was originally established for the little children of the London streets. During this period there were from seven to nine hundred children maintained at the cost of this institution, some in London and some at nurse in the country[525]. At Bristol there were two establishments of the same kind. Queen Elizabeth's Hospital was founded by a citizen named John Carr after the model of Christ's Hospital in London. The
  • 80. γ. The able-bodied poor. 5. Relief given to prisoners. boys were subject to the same regulations and still wear the same blue and yellow dress[526]. The Red Maid's School was endowed by the will of John Whitson in 1621. It was to consist of a matron and forty girls. The children were to learn to read and sew and do such other work as the matron and the Mayor's wife should approve. They were to be apprenticed for eight years, to wear clothes of red cloth, and attend on the wives of the Mayor and aldermen on state occasions[527]. In Plymouth, Exeter, and Norwich also there were similar institutions, but they seem to have only existed in the large towns. Both in the country and towns orphaned and deserted children were generally "boarded out" until they were old enough to be apprenticed, and payments were made for them from the rates amounting to about a shilling a week. Children were thus very well provided for, and their training was considered a matter of national concern. Parents, whether they were very poor or not, were compelled to send their children to work or school and either to apprentice them or to find situations for them. We are apt to consider popular education an exclusively modern movement, but in this, as in many other matters, the aims of the seventeenth century anticipate those of the nineteenth. They had ideas which were very different from those of to-day as to the kind of training which was necessary, but they attached an equal importance to the necessity of training. The Town Council of Norwich and the justices of Hertfordshire and Norfolk took energetic action in the matter. We will now see how the administration of the time affected the able-bodied poor. The help given to the unemployed is by far the most important part of this relief, but some aid was also given to prisoners. The prisoners of the sixteenth century must have suffered great hardships. No adequate means seem to have existed for their maintenance. Their friends supported them, and under certain regulations they were allowed to beg. Several statutes made in the
  • 81. Welcome to our website – the perfect destination for book lovers and knowledge seekers. We believe that every book holds a new world, offering opportunities for learning, discovery, and personal growth. That’s why we are dedicated to bringing you a diverse collection of books, ranging from classic literature and specialized publications to self-development guides and children's books. More than just a book-buying platform, we strive to be a bridge connecting you with timeless cultural and intellectual values. With an elegant, user-friendly interface and a smart search system, you can quickly find the books that best suit your interests. Additionally, our special promotions and home delivery services help you save time and fully enjoy the joy of reading. Join us on a journey of knowledge exploration, passion nurturing, and personal growth every day! ebookbell.com