0% found this document useful (0 votes)
7 views76 pages

58516940

The document promotes instant access to various eBooks related to the Rust programming language, including titles like 'Rust in Action' and 'Refactoring to Rust.' It provides links for downloading these eBooks in multiple formats and highlights the content structure of 'Rust in Action,' which covers Rust language features, systems programming, and concurrent programming. Additionally, it encourages reader feedback for improving the book's content and discusses the adoption of Rust by major tech companies.

Uploaded by

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

58516940

The document promotes instant access to various eBooks related to the Rust programming language, including titles like 'Rust in Action' and 'Refactoring to Rust.' It provides links for downloading these eBooks in multiple formats and highlights the content structure of 'Rust in Action,' which covers Rust language features, systems programming, and concurrent programming. Additionally, it encourages reader feedback for improving the book's content and discusses the adoption of Rust by major tech companies.

Uploaded by

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

Instant Ebook Access, One Click Away – Begin at ebooknice.

com

(Ebook) Rust in Action - MEAP Ver. 16 by TS


McNamara ISBN 9781617294556, 1617294551

https://ebooknice.com/product/rust-in-action-meap-
ver-16-29258470

OR CLICK BUTTON

DOWLOAD EBOOK

Get Instant Ebook Downloads – Browse at https://ebooknice.com


Instant digital products (PDF, ePub, MOBI) ready for you
Download now and discover formats that fit your needs...

Start reading on any device today!

(Ebook) Rust in Action by T.S. McNamara ISBN 9781617294556, 1617294551

https://ebooknice.com/product/rust-in-action-23285108

ebooknice.com

(Ebook) Rust in Action: Systems programming concepts and techniques by Tim McNamara
ISBN 9781617294556, 1617294551

https://ebooknice.com/product/rust-in-action-systems-programming-concepts-and-
techniques-42970346

ebooknice.com

(Ebook) Refactoring to Rust, MEAP V05 by Lily Mara ISBN 9781617299018, 1617299014

https://ebooknice.com/product/refactoring-to-rust-meap-v05-47531982

ebooknice.com

(Ebook) Rust Design Patterns (MEAP V02) by Brenden Matthews ISBN 9781633437463,
1633437469

https://ebooknice.com/product/rust-design-patterns-meap-v02-54294038

ebooknice.com
(Ebook) Rust Web Development (MEAP V06) by Bastian Gruber ISBN 9781617299001,
1617299006

https://ebooknice.com/product/rust-web-development-meap-v06-42603006

ebooknice.com

(Ebook) Quantum Computing In Action (MEAP v09) by Johan Vos

https://ebooknice.com/product/quantum-computing-in-action-meap-v09-23285606

ebooknice.com

(Ebook) Refactoring to Rust - MEAP Version 5 by Lily Mara ISBN 9781617299018,


1617299014

https://ebooknice.com/product/refactoring-to-rust-meap-version-5-43786000

ebooknice.com

(Ebook) Rust Power Tools (MEAP V01) by Sam Van Overmeire ISBN 9781633437494,
1633437493

https://ebooknice.com/product/rust-power-tools-meap-v01-51048494

ebooknice.com

(Ebook) Elasticsearch in Action, Second Edition (MEAP V13) by Madhusudhan Konda

https://ebooknice.com/product/elasticsearch-in-action-second-edition-
meap-v13-50699840

ebooknice.com
MEAP VERSION 16
ABOUT THIS MEAP

You can download the most up-to-date version of your electronic


books from your Manning Account at account.manning.com. For
customer support write to support@manning.com.

© Manning Publications Co. We welcome reader comments about


anything in the manuscript - other than typos and other simple
mistakes. These will be cleaned up during production of the book by
copyeditors and proofreaders.

https://livebook.manning.com/#!/book/rust-in-action/discussion
WELCOME

Dear Reader,

Thanks for taking a chance and buying this early release book on the
Rust programming language and the internals of computer systems.
I hope that you'll be rewarded with a fun, informative read!

Part 1: Rust Language Distinctives will provide a quick-fire


introduction to the Rust language by working through projects that
begin to introduce concepts that are expanded upon later in the
book, such as implementing a File API.

Part 2: Systems Programming from the Ground Up (Almost) will shift


your focus towards the computer. You will learn how data is
represented at various levels between the application, operating
system and hardware. Rust language features will be introduced as
required.

A note about Chapter 6: This chapter should be considered a work in


progress. It covers lots of ground. Readers progress from learning
what a pointer is to benchmarking memory allocations with system
utilities for Linux. Some of the explanations are terse... perhaps too
terse.

We believe that the content is interesting and relevant to


professional programmers, but are considering how it should be
expanded and refactored to be most relevant to the book's readers.
The author and the editorial team are very interested in your views
about what works and what needs more work.
Part 3: Concurrent and Parallel Programming will walk through the
tools that computers offer to get work done in parallel. Its primary
goal will be to explain how multiple threads can cooperate and
coordinate. A large example— building a graph that can be
distributed in multiple ways—will be extended throughout several
chapters.

Finally, Part 4: Extending Applications Up and Out will show Rust


being used to build up software components to extend large
software projects. These projects demonstrate systems
programming “with the system” rather than systems programming
“of the system”. Part 4 will deal with the complexities of handling
multiple CPU/OS pairs from the same code base.

As a MEAP reader, you have a unique opportunity to contribute to


the book's development. All feedback is greatfully received, but
please remember that there will be a human receiving the message.
The best channel is the Manning liveBook's Discussion Forum. I'm
also active on Twitter (@timClicks), Reddit (/u/timclicks) and the
Rust Discourse forum (https://users.rust-lang.org/u/timclicks).

Thank you once again for choosing to purchase the book. It's a
privilege to ride a short way with you along your computing journey.

—Tim McNamara
BRIEF TABLE OF CONTENTS

1 Introducing Rust

Part 1: Rust Language Distinctives


2 Language Foundations
3 Compound Data Types

4 Lifetimes, Ownership and Borrowing

Part 2: Demystifying Systems Programming


5 Data in Depth

6 Memory
7 Files & Storage

8 Networking
9 Time and Time Keeping

10 Processes, Threads and Containers


11 Kernel

12 Signals, Interrupts and Exceptions


1 INTRODUCING RUST

This chapter covers:

Introducing Rust’s features and goals


Exposing Rust’s syntax
Discussing where to use Rust and when to avoid it
Building your first Rust program
Explaining how Rust compares to object-oriented and
wider languages

Welcome to Rust—the empowering programming language. Once


you scratch its surface, you will not only find a programming
language with unparalleled speed and safety, but one that is still
comfortable to use. Your investment in learning Rust will be
rewarded!

When you begin to program in Rust, it’s likely that you will want to
continue to do so. And this book, Rust in Action, will build your
confidence as a Rust programmer. But, it will not teach you how to
program from the beginning. This book is intended to be read by
people who are considering Rust as their next language, and for
those who enjoy implementing practical working examples. Here is a
list of some of the larger examples this book covers:

Mandelbrot set renderer


A grep clone
CPU emulator
Generative art
A database
HTTP, NTP, and hexdump clients
LOGO language interpreter
Operating system kernel

As you may gather from scanning through that list, reading this book
will teach you more than Rust. It also introduces you to systems
programming and low-level programming. Learning some of the
concepts from these areas will benefit your Rust programming
journey because much of the Rust community assumes that you
already have that knowledge. As you work through Rust in Action,
you’ll learn about the role of an operating system (OS), how a CPU
works, how computers keep time, what pointers are, and what a
data type is. You will gain an understanding of how the computer’s
internal systems interoperate. Learning more than syntax, you will
also see why Rust was created and the challenges that it addresses.

1.1 WHERE IS RUST USED?


Rust has won the “most loved programming language” award in
Stack Overflow’s annual developer survey in 2016, 2017, 2018, 2019,
and 2020. Perhaps that’s why large technology leaders such as the
following have adopted Rust:

Amazon Web Services (AWS) runs its serverless


computing offerings, AWS Lambda and AWS Fargate, with
[1]
Rust.
Cloudflare develops many of its services, including its
public DNS, serverless computing, and packet inspection
[2]
offerings with Rust.
Dropbox rebuilt its backend warehouse, which manages
[3]
exabytes of storage, with Rust.
Google develops portions of the Chrome OS and Fuchsia
[4]
operating systems in Rust.
Facebook uses Rust to power Facebook’s web, mobile, and
API services, as well as parts of HHVM, the HipHop virtual
[5]
machine used by the Hack programming language.
Microsoft writes components of its Azure platform
including a security daemon for its Internet of Things
[6]
(IoT) service in Rust.
Mozilla uses Rust to enhance the Firefox web browser,
which contains 15 million lines of code. Mozilla’s first two
Rust-in-Firefox projects, its MP4 metadata parser and text
encoder/decoder, led to overall performance and stability
improvements.

GitHub’s npm, Inc., uses Rust to deliver “upwards of 1.3


[7]
billion package downloads per day.`"
Oracle developed a container run time with Rust to
overcome problems with the Go reference
[8]
implementation.
Samsung, via its subsidiary SmartThings, uses Rust in its
“Hub,” which is the firmware backend for its Internet of
Things (IoT) service.

Rust is also productive enough for fast-moving startups to deploy it.


Here’s a few examples:

Sourcegraph uses Rust to serve syntax highlighting across


[9]
all of its languages.
Figma employs Rust in the performance-critical
[10]
components of its multi-player server.
Parity develops its client to the Ethereum blockchain with
[11]
Rust.

As well, Rust supports WebAssembly (Wasm), a standard for


deploying apps as a first-class citizen into browsers without
JavaScript. Wasm allows you to compile and deploy your Rust
project to a server, IoT devices, mobile devices, and a browser.

[1] See “Firecracker: Secure and fast microVMs for serverless computing,”
https://firecracker-microvm.github.io/

[2] See “Rust at Cloudflare,” https://news.ycombinator.com/item?id=17077358

[3] See “The Epic Story of Dropbox’s Exodus From the Amazon Cloud Empire,”
https://www.wired.com/2016/03/epic-story-dropboxs-exodus-amazon-cloud-
empire/

[4] See “crosvm—The Chrome OS Virtual Machine Monitor,”


https://chromium.googlesource.com/chromiumos/platform/crosvm/ and “Fuchsia
Rust Crates,”
https://fuchsia.googlesource.com/fuchsia/+/master/docs/development/language
s/rust/crates.md

[5] See “HHVM 4.20.0 and 4.20.1,” https://hhvm.com/blog/2019/08/27/hhvm-


4.20.0.html

[6] See https://github.com/Azure/iotedge/tree/master/edgelet

[7] See "`Rust Case Study: Community makes Rust an easy choice for npm,”
https://www.rust-lang.org/static/pdfs/Rust-npm-Whitepaper.pdf

[8] See “Building a Container Runtime in Rust,”


https://blogs.oracle.com/developers/building-a-container-runtime-in-rust

[9] See “HTTP code syntax highlighting server written in Rust,”


https://github.com/sourcegraph/syntect_server
[10] See “Rust in Production at Figma,” https://www.figma.com/blog/rust-in-
production-at-figma/

[11] See “The fast, light, and robust EVM and WASM client,”
https://github.com/paritytech/parity-ethereum

1.2 ADVOCATING FOR RUST AT WORK


What is it like to advocate for Rust at work? This 2017 snippet
discusses advocating for Rust at Google within the Chrome OS:

[12]
Excerpt from a Hacker News comment thread

indy on Sept 27, 2017 Is Rust an officially sanctioned language at Google?

zaxcellent on Sept 27, 2017


Author here: Rust is not officially sanctioned at Google, but there
are pockets of folks using it here. The trick with using Rust in
this component was convincing my coworkers that no other language
was right for job, which I believe to be the case in this instance.

That being said, there was a ton of work getting Rust to play nice
within the Chrome OS build environment. The Rust folks have been super
helpful in answering my questions though.

ekidd on Sept 27, 2017


> The trick with using Rust in this component was convincing my
coworkers that no other language was right for job, which I
believe to be the case in this instance.

I ran into a similar use case in one of my own projects—a vobsub


subtitle decoder, which parses complicated binary data, and which
I someday want to run as web service. So obviously, I want to
ensure that there are no vulnerabilities in my code.

I wrote the code in Rust, and then I used 'cargo fuzz' to try
and find vulnerabilities. After running a billion(!) fuzz
iterations, I found 5 bugs (see the 'vobsub' section of the
trophy case for a list https://github.com/rust-fuzz/trophy-case).

Happily, not one of those bugs could actually be escalated into


an actual exploit. In each case, Rust's various runtime checks
successfully caught the problem and turned it into a controlled
panic. (In practice, this would restart the web server cleanly.)

So my takeaway from this was that whenever I want a language (1)


with no GC, but (2) which I can trust in a security-critical
context, Rust is an excellent choice. The fact that I can
statically link Linux binaries (like with Go) is a nice plus.

From this excerpt, we can see that language adoption has been
“bottom up” by engineers looking to overcome technical challenges.
Skepticism with using Rust for internal side-projects from colleagues
has been overcome, thus gaining in first-hand experience and
measurable performance data. And in the time since late 2017, Rust
has continued to mature and strengthen. It has become an accepted
part of Google’s technology landscape; it is now an officially
sanctioned language within the Fuchsia OS project.

[12] See “Chrome OS KVM—A component written in Rust,”


https://news.ycombinator.com/item?id=15346557

1.3 A TASTE OF THE LANGUAGE


This section gives you a chance to experience Rust firsthand. We
start by understanding how to use the compiler and then move on to
writing a quick program next and full projects in later chapters.

Note
To install Rust, use the official installers provided at
https://rustup.rs/.
1.3.1 Cheating your way to “Hello, world!”
The first thing that most programmers do when they reach for a new
programming language is to learn how to print “Hello, world!” to the
console. You’ll do that too, but with flair. You’ll verify that everything
is in working order before you encounter annoying syntax errors.

If you use Windows, open the Rust command prompt that is


available in the Start menu after installing Rust. Then execute this
command:

C:\> cd %TMP%

If you are running Linux or macOS, please open a Terminal window.


Once open, please enter the following:

$ cd $TMP

From this point forward, the commands for all operating systems
should be the same. If you installed Rust correctly, the following
three commands will display “Hello, world!” on the screen (as well as
a bunch of other output):

$ cargo new hello


$ cd hello
$ cargo run

Here is an example of what the entire code looks like for Windows:

C:\> cd %TMP%

C:\Users\Tim\AppData\Local\Temp\> cargo new hello


Created binary (application) `hello` project

C:\Users\Tim\AppData\Local\Temp\> cd hello
C:\Users\Tim\AppData\Local\Temp\hello\> cargo run
Compiling hello v0.1.0 (file:///C:/Users/Tim/AppData/Local/Temp/hello)
Finished dev [unoptimized + debuginfo] target(s) in 0.32s
Running `target\debug\hello.exe`
Hello, world!

And on Linux, the code would look like this:

$ cd $TMP

$ cargo new hello


Created binary (application) `hello` package

$ cd hello

$ cargo run
Compiling hello v0.1.0 (/home/tsm/hello)
Finished dev [unoptimized + debuginfo] target(s) in 0.26s
Running `target/debug/hello`
Hello, world!

If you have reached this far, fantastic! You have run your first Rust
code without needing to write any Rust. Let’s take a look at what’s
just happened.

cargo is a tool that provides both a build system and a package


manager. That is, cargo knows how to execute rustc (the Rust
compiler) to convert your Rust code into executable binaries or
shared libraries. cargo new creates a project for you that follows a
standard template. Your directory structure will have been changed
to something that looks like this:

$ tree hello
hello
├── Cargo.toml
└── src
└── main.rs

1 directory, 2 files
All Rust crates begin with the same structure. In the base directory,
a file called Cargo.toml describes the project’s metadata, such as the
project’s name, its version, and its dependencies. Source code
appears in the src directory. Rust source code files use the .rs
filename extension.

The next command that you executed was cargo run. This line is
much simpler to grasp, but cargo actually did much more work than
you realized. You asked cargo to run the project. As there was
nothing to actually run when you invoked the command, it decided
to compile the code in debug mode on your behalf to provide
maximal error information. As it happens, the src/main.rs file always
includes a “Hello, world!” stub. The result of that compilation was a
file called hello (or hello.exe). The hello file was executed, and the
result printed to your screen.

For the curious, our project’s directory structure has changed a great
deal. We now have a Cargo.lock file in the base of our project and a
target/ directory. Both that file and the directory are managed by
cargo. Because these are artifacts of the compilation process, we
won’t need to touch these. Cargo.lock is a file that specifies the
exact version numbers of all the dependencies so that future builds
are reliably built the same way until Cargo.toml is modified.

$ tree --dirsfirst hello


hello
├── src
│ └── main.rs
├── target
│ └── debug
│ ├── build
│ ├── deps
│ ├── examples
│ ├── native
│ └── hello
├── Cargo.lock
└── Cargo.toml
For getting things up and running, well done! Now that we’ve
cheated our way to “Hello, World!”, let’s get there via the long way.

1.3.2 Your first Rust program


For our first program, we want to write something that outputs the
following text:

Hello, world!
Grüß Gott!
ハロー・ワールド

You have probably seen the first line in your travels. The other two
are there to highlight few of Rust’s features: easy iteration and built-
in support for Unicode.

For this program, we will use cargo as in the previous section. To


start, open a console window and move into a temporary directory
(cd /tmp/ or cd %TMP% on Windows). After that, type the following at
the command prompt.

$ cargo new hello2


$ cd hello2

Now open the file hello2/src/main.rs in a text editor. Replace the text
in that file with the text in the following listing. You’ll find the source
code for this listing in the file ch1/ch1-hello2.rs (see section 1.4 for
access to this book’s source files).

Listing 1.1. “Hello World!” in three languages

fn greet_world() {
println!("Hello, world!"); ①

let southern_germany = "Grüß Gott!"; ②


let japan = "ハロー・ワールド"; ③
let regions = [southern_germany, japan]; ④

for region in regions.iter() { ⑤


println!("{}", &region); ⑥
}
}

fn main() {
greet_world(); ⑦
}

① The exclamation mark indicates the use of a macro, which we’ll


discuss shortly.
② Assignment in Rust, more properly called variable binding, uses
the let keyword.
③ Unicode support is provided out of the box.
④ Array literals use square brackets.
⑤ Many types can have an iter() method to return an iterator.
⑥ The ampersand (&) borrows the region value.
⑦ Calls a function. Note that parentheses follow the function name.

Now that our code is updated, execute cargo run from the hello2/
directory. You should see three greetings. Let’s take a few moments
to touch on some of the elements in listing 1.1.

One of the first things that you are likely to notice is that strings in
Rust are able to include a wide range of characters. Strings are UTF-
8. This means that you can use non-English languages with relative
ease.

The one character that might look out of place is the exclamation
mark after println. If you have programmed in Ruby, you may be
used to thinking that it is used to signal a destructive operation. In
Rust, it signals the use of a macro. Macros can be thought of as sort
of fancy functions for now. These offer the ability to avoid boilerplate
code. In the case of println!, there is a lot of type detection going
on under the hood so that arbitrary data types can be printed to the
screen.

1.4 DOWNLOADING THE BOOK’S SOURCE


CODE
In order to follow along with the examples in this book, you might
want to access the source code for the listings. For your
convenience, source code for every example is available from two
sources:

https://manning.com/books/rust-in-action
https://github.com/rust-in-action/code

1.5 WHAT DOES RUST LOOK AND FEEL LIKE?


Rust is the programming language that allows Haskell and Java
programmers to get along. Rust comes close to the high-level,
expressive feel of dynamic languages like Haskell and Java while
achieving bare-metal performance. We looked at a “Hello, world!”
example in section 1.3, so let’s try something slightly more complex
to get a better feel for Rust’s features. Listing 1.2 provides a quick
look at what Rust can do for basic text processing. Some features to
notice include

Common control flow mechanisms—This includes for


loops and the continue keyword.
Method syntax—Although Rust is not object-oriented as it
does not support inheritance, it carries over this feature of
object-oriented languages.
Higher-order programming—Functions can both accept
and return functions. For example, line 19 includes a
closure, also known as an anonymous function or λ
(lambda) function.
Type annotations—Although relatively rare, these are
occasionally required as a hint to the compiler (for
example, line 28).
Conditional compilation—In the listing, lines 22-24 are not
included in release builds of the program.
Implicit return—Rust provides a return keyword, but it’s
usually omitted. Rust is an expression-based language.

Note
The source code for this listing is in the ch1/ch1-
penguins/src/main.rs file.

Listing 1.2. Example of Rust code showing some basic


processing of CSV data

fn main() { ①
let penguin_data ="\
common name,length (cm)
Little penguin,33
Yellow-eyed penguin,65
Fiordland penguin,60
Invalid,data
";

let records = penguin_data.lines();

for (i, record) in records.enumerate() {


if i == 0 || record.trim().len() == 0 { ②
continue;
}

let fields: Vec<_> = record ③


.split(',') ④
.map(|field| field.trim()) ⑤
.collect(); ⑥

if cfg!(debug_assertions) { ⑦
// following line should not exceed 55 chars; please add a line break
and move annotation marker as needed
eprintln!("debug: {:?} -> {:?}", record, fields); ⑧
}

let name = fields[0]; ⑨

// following line should not exceed 55 chars; please add a line break
and move annotation marker as needed
let maybe_length: Result<f32, _> = fields[1].parse(); ⑩

if maybe_length.is_err() { ⑪
continue;
}

let length = maybe_length.unwrap(); ⑫

println!("{}, {}cm", name, length); ⑬


}
}

① Executable projects require a main() function.


② Skips header row and lines with only whitespace
③ A Vec type is shorthand for vector. Vectors are arrays that
dynamically expand when needed. The underscore asks the
compiler to infer the vector’s element type.
④ Splits the record into substrings
⑤ For loops, you can use higher-order functions. This line trims the
whitespace from every field.
⑥ “Collects” the results of an iterator into a vector
⑦ For debugging, include this code block. The ! indicates a macro
invocation. Macros, similar to functions, return code rather than
values and are often used to simplify common patterns.
⑧ Prints to standard error. The {:?} syntax requests the default
debugging representation for the two types as output.
⑨ Rust supports indexing collections with integers.
⑩ Parses strings into other types, using the type information
provided on the left side. This either returns a value or an error
value wrapped in a Result. The underscore requests the compiler
to infer the error type itself.
⑪ Skips any invalid data
⑫ Unwraps the f32 value from the Result
⑬ Prints to stdout. The {} syntax indicates that Rust should use a
programmer-defined method to represent the value as a string,
rather than its debug representation available with {:?}.

Converting source code into an executable file is called compiling. To


compile Rust code, we need to install the Rust compiler and run it
against the source code. To compile listing 1.2, follow these steps:

1. Open a console prompt (e.g., cmd.exe, PowerShell, Terminal, or


Alacritty)
2. Move to the ch1/ch1-penguins directory (not ch1/ch1-
penguins/src) of the source code you downloaded in section 1.4
3. Execute cargo run

Listing 1.3. Output from listing 1.2 after running cargo run

$ cargo run
// code lines without annotations are limited to 76 chars in order to fit
the
printed page. Following line needs a line break
Compiling ch1-penguins v0.1.0 (/path/to/rust-in-action/code/ch1/ch1-
penguins)
Finished dev [unoptimized + debuginfo] target(s) in 0.40s
Running `target/debug/ch1-penguins`
debug: " Little penguin,33" -> ["Little penguin", "33"]
Little penguin, 33cm
debug: " Yellow-eyed penguin,65" -> ["Yellow-eyed penguin", "65"]
Yellow-eyed penguin, 65cm
debug: " Fiordland penguin,60" -> ["Fiordland penguin", "60"]
Fiordland penguin, 60cm
debug: " Invalid,data" -> ["Invalid", "data"]
You probably noticed the distracting lines starting with debug:. We
can eliminate these by compiling a release build using cargo’s --
release flag. This conditional compilation functionality is provided by
the cfg!(debug_assertions) { … } block within lines 22-24 of the
following listing.

Listing 1.4. Output from creating a release build of listing


1.2

$ cargo run --release


Compiling ch1-penguins v0.1.0 (/path/to/code/ch1/ch1-penguins)
Finished release [optimized] target(s) in 0.34s
Running `target/release/ch1-penguins`
Little penguin, 33cm
Yellow-eyed penguin, 65cm
Fiordland penguin, 60cm

It’s possible to further reduce the output by adding the -q flag (-q is
shorthand for “quiet”). The following snippet shows the syntax:

$ cargo run -q --release


Little penguin, 33cm
Yellow-eyed penguin, 65cm
Fiordland penguin, 60cm

Should I use cargo or rustc to compile code?

In a strict sense, rustc is the Rust compiler. The preceding examples don’t use it
though. Instead, the examples interact with cargo. cargo provides a simple
interface, invoking rustc on our behalf.
To see what cargo passes to rustc, add the --verbose flag:

$ cd code/ch1/ch1-penguins
$ cargo run --verbose
Compiling ch1-penguins v0.1.0 (rust-in-action/code/ch1/ch1-penguins)
// line breaks needed in following; 76 max characters including spaces per
each line
Running `rustc --crate-name ch1_penguins --edition=2018 src/main.rs
--error-format=json --json=diagnostic-rendered-ansi --crate-type bin
--emit=dep-info,link -Cbitcode-in-rlib=no -C debuginfo=2 -C
metadata=390c3b75f851c687 -C extra-filename=-390c3b75f851c687
--out-dir rust-in-action/code/ch1/ch1-penguins/target/debug/deps
-C incremental=rust-in-action/code/ch1/ch1-penguins/target/debug
/incremental
-L dependency=rust-in-action/code/ch1/ch1-penguins/target/debug/deps`
Finished dev [unoptimized + debuginfo] target(s) in 0.43s
Running `target/debug/ch1-penguins`
debug: " Little penguin,33" -> ["Little penguin", "33"]
Little penguin, 33cm
debug: " Yellow-eyed penguin,65" -> ["Yellow-eyed penguin", "65"]
Yellow-eyed penguin, 65cm
debug: " Fiordland penguin,60" -> ["Fiordland penguin", "60"]
Fiordland penguin, 60cm
debug: " Invalid,data" -> ["Invalid", "data"]

Listing 1.1 and listing 1.2 were chosen to pack as many


representative features of Rust into the examples as possible.
Hopefully these demonstrated that Rust programs have a high-level
feel, paired with a low-level performance. Let’s take a step back from
specific language features now and consider some of the thinking
behind the language and where it fits within the programming
language ecosystem.

1.6 WHAT IS RUST?


Rust’s distinguishing feature as a programming language is its ability
to prevent invalid data access at compile time. Research projects by
Microsoft’s Security Response Center and the Chromium browser
project both suggest that issues relating to invalid data access
[13]
account for approximately 70% of serious security bugs. Rust
eliminates that class of bugs. It guarantees that your program is
memory safe without imposing any run time costs. Other languages
can provide this level of safety, but these require adding checks that
execute while your program is running, thus slowing it down.
Rust’s distinguishing feature—as the professional community
acknowledges—is its willingness to explicitly include values into its
decision-making process. This ethos of inclusion is pervasive. Public
messaging is welcoming. All interactions within the Rust community
are governed by its code of conduct. Even the Rust compiler’s error
messages are ridiculously helpful.

Until late 2018, visitors to the Rust homepage were greeted with the
(technically heavy) message, “Rust is a systems programming
language that runs blazingly fast, prevents segfaults and guarantees
thread safety.” At that point, the community implemented a change
to its wording to put its users (and its potential users) at the center
(table 1.1).

Table 1.1. Rust slogans over time. As Rust has developed its
confidence, it has increasingly embraced the idea of acting
as a facilitator and supporter of everyone wanting to
achieve their programming aspirations.
Until late 2018 From that point onward

“Rust is a systems “Empowering everyone to


programming language build reliable and efficient
that runs blazingly fast, software.”
prevents segfaults and
guarantees thread safety.”

Rust is labelled as a systems programming language, which tends to


be seen as quite a specialized, almost esoteric, branch of
programming. However, many Rust programmers have discovered
that the language is applicable to many other domains. Safety,
productivity, and control are useful in all software engineering
projects. Moreover, the Rust community’s inclusiveness means that
the language benefits from a steady stream of new voices with
diverse interests.

Let’s flesh out those three goals: safety, productivity, and control.
What are these and why do these matter?

1.6.1 Goal of Rust: Safety


Rust programs are free from
Dangling pointers—Live references to data that has
become invalid over the course of the program (see listing
1.5)
Data races—Inability to determine how a program will
behave from run to run because external factors are
changing (see listing 1.6)
Buffer overflow—Attempt to access the 12th element of an
array with only 6 elements (see listing 1.7)
Iterator invalidation—An issue caused by something that is
iterated over after being altered mid-way through (see
listing 1.8)

When programs are compiled in debug mode, Rust also protects


against integer overflow. What is integer overflow? Well, integers
can only represent a finite set of numbers; these have a fixed-width
in memory. Integer overflow is what happens when the integers hit
their limit and flow over to the beginning again.

The following listing shows a dangling pointer. Note that you’ll find
this source code in the ch1/ch1-cereals/src/main.rs file.

Listing 1.5. Attempting to create a dangling pointer

#[derive(Debug)] ①
enum Cereal { ②
Barley, Millet, Rice,
Rye, Spelt, Wheat,
}

fn main() {
let mut grains: Vec<Cereal> = vec![]; ③
grains.push(Cereal::Rye); ④
drop(grains); ⑤

println!("{:?}", grains); ⑥
}

① Allows the println! macro to print the Cereal enum


② An enum (enumeration) is a type with a fixed number of legal
variants.
③ Initializes an empty vector of Cereal
④ Adds one item to the grains vector
⑤ Deletes grains and its contents
⑥ Attempts to access the deleted value

Listing 1.5 contains a pointer within grains. In the listing,


Vec<Cereal> is implemented with an internal pointer to an underlying
array. But the listing does not compile. An attempt to do so triggers
an error message that complains about attempting to “borrow” a
“moved” value. Learning how to interpret that error message and to
fix the underlying error are topics for the pages to come. Here’s the
compiled code:

$ cargo run
Compiling ch1-cereals v0.1.0 (/rust-in-action/code/ch1/ch1-cereals)
error[E0382]: borrow of moved value: `grains`
--> src/main.rs:12:22
|
8 | let mut grains: Vec<Cereal> = vec![];
// following line needs a line break (76 char max)
| ---------- move occurs because `grains` has type
`std::vec::Vec<Cereal>`,
which does not implement the `Copy` trait
9 | grains.push(Cereal::Rye);
10 | drop(grains);
| ------ value moved here
11 |
12 | println!("{:?}", grains);
| ^^^^^^ value borrowed here after move

error: aborting due to previous error

For more information about this error, try `rustc --explain E0382`.
error: could not compile `ch1-cereals`.
Listing 1.6 shows an example of a data race condition. If you
remember, this condition results from the inability to determine how
a program behaves from run to run due to external factors changing.
You’ll find this code in the ch1/ch1-race/src/main.rs file.

Listing 1.6. Example of how Rust prevents a data race


condition

use std::thread; ①

fn main() {
let mut data = 100;

thread::spawn(|| { data = 500; }); ②


thread::spawn(|| { data = 1000; }); ②

println!("{}", data);
}

① Brings the standard library’s threading implementation into local


scope.
② thread::spawn() takes a closure as an argument.

If you are unfamiliar with the term “thread,” the upshot is that this
code is not deterministic. It’s impossible to know what data will be
like when main() exits. In the listing, the closure for thread::spawn()
is denoted by vertical bars and curly braces (e.g., || {…}), limiting
the returned data calls to 500 and 1,000, respectively.

Attempting to compile listing 1.6 results in a large stampede of error


messages. Rust does not allow multiple places in an application to
have write access to data. Listing 1.6 attempts to allow this in three
places: once within the main thread running main() and once in each
child thread created by thread::spawn(). Here’s the compiler
message:
$ cargo run
Compiling ch1-race v0.1.0 (rust-in-action/code/ch1/ch1-race)
// add line break to following (76 char max)
error[E0373]: closure may outlive the current function, but it borrows
`data`,
which is owned by the current function
--> src/main.rs:6:19
|
6 | thread::spawn(|| { data = 500; });
| ^^ ---- `data` is borrowed here
| |
| may outlive borrowed value `data`
|
note: function requires argument type to outlive `'static`
--> src/main.rs:6:5
|
6 | thread::spawn(|| { data = 500; });
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// add line break to following (76 char max)
help: to force the closure to take ownership of `data` (and any other
referenced
variables), use the `move` keyword
|
6 | thread::spawn(move || { data = 500; });
| ^^^^^^^

... ①

error: aborting due to 4 previous errors

Some errors have detailed explanations: E0373, E0499, E0502.


For more information about an error, try `rustc --explain E0373`.
error: could not compile `ch1-race`.

① Three other errors omitted.

Listing 1.7 provides an example of a buffer overflow (attempting to


access the 12th element of an array of only 6 elements, for
example). The source code for this listing is in the file ch1/ch1-
fruit/src/main.rs.
Listing 1.7. Example of invoking a panic via a buffer
overflow

fn main() {
let fruit = vec!['🥝', '🍌', '🍇'];
let buffer_overflow = fruit[4]; ①

assert_eq!(buffer_overflow, '🍉') ②
}
// added extra line spaces above for longish annotations

① This code will “panic” rather than assign buffer_overflow to an


invalid memory location.
② assert_eq!() allows assertions, but the two sides of assert_eq!()
must equal or the program panics.

When listing 1.7 is compiled and executed, you’ll encounter this


error message:

$ cargo run
Compiling ch1-fruit v0.1.0 (/rust-in-action/code/ch1/ch1-fruit)
Finished dev [unoptimized + debuginfo] target(s) in 0.31s
Running `target/debug/ch1-fruit`
// the following two lines need line breaks (76 char max per line)
thread 'main' panicked at 'index out of bounds: the len is 3 but the index
is 4',
src/main.rs:3:25
note: run with `RUST_BACKTRACE=1` environment variable to display a
backtrace

Listing 1.8 shows an example of iterator invalidation, where an issue


is caused by something that’s iterated over after being altered mid-
way through. The source code for this listing is in ch1/ch1-
letters/src/main.rs.
Listing 1.8. Attempting to modify an iterator while
iterating over it

fn main() {
let mut letters = vec![ ①
"a", "b", "b"
];

for letter in letters {


println!("{}", letter);
letters.push(letter.clone()); ②
}
}

① Initializes a vector and allows mutation (alteration or


modification)
② Creates a new copy of letter and appends it to the end of letters

Listing 1.8 fails to compile because Rust will not allow letters to be
modified within the iteration block. Here’s the error message:

$ cargo run
Compiling ch1-letters v0.1.0 (/rust-in-action/code/ch1/ch1-letters)
error[E0382]: borrow of moved value: `letters`
--> src/main.rs:8:7
|
2 | let mut letters = vec![
// add line break below (76 char max)
| ----------- move occurs because `letters` has type
`std::vec::Vec<&str>`,
which does not implement the `Copy` trait
...
6 | for letter in letters {
| -------
| |
| value moved here
// add line breaks below (55 char max for line with <1>)
| help: consider borrowing to avoid moving into the for
loop:
`&letters` ①
7 | println!("{}", letter);
8 | letters.push(letter.clone());
| ^^^^^^^ value borrowed here after move
error: aborting due to previous error

For more information about this error, try `rustc --explain E0382`.
error: could not compile `ch1-letters`.

To learn more, run the command again with --verbose.

① In this case, the suggestion doesn’t help. It recommends a read-


only reference (e.g., &letters). Using a read/write reference (e.g.,
&mut letters) also fails to compile.

Knowing that a language is safe provides programmers with a


degree of liberty. Because they know their program won’t implode,
they become much more willing to experiment. Within the Rust
community, this liberty has spawned the saying “fearless
concurrency.”

1.6.2 Goal of Rust: Productivity


When given a choice, Rust prefers the option that is easiest for the
developer. Many of its more subtle features are productivity boosts.
But programmer productivity is a difficult concept to demonstrate
with an example in a book. Let’s start with something that can snag
beginners: using assignment (=) within an expression that should
use an equality (==) test.

fn main() {
let a = 10;

if a = 10 {
println!("a equals ten");
}
}

In Rust, the preceding code would fail to compile. The Rust compiler
generates the following message:
error[E0308]: mismatched types
--> src/main.rs:4:8
|
4 | if a = 10 {
| ^^^^^^
| |
| expected `bool`, found `()`
| help: try comparing for equality: `a == 10`

error: aborting due to previous error

For more information about this error, try `rustc --explain E0308`.
error: could not compile `playground`.

To learn more, run the command again with --verbose.

At first, “mismatched types” might feel like a strange error message


to encounter. Surely we can test variables for equality against
integers.

After some thought, it becomes apparent why the if test receives


the wrong type. The if is not receiving an integer. It’s receiving the
result of an assignment. In Rust, this is the blank type: (). () is
[14]
pronounced “unit.`"

When there is no other meaningful return value, expressions return


(). As the following shows, adding a second equals sign on line 4
results in a working program that prints a equals ten.

fn main() {
let a = 10;

if a == 10 { ①
println!("a equals ten");
}
}

① Using a valid assignment operator (==) allows the program to


compile.
Rust has many ergonomic features. It offers generics, sophisticated
[15]
data types, pattern matching, and closures. Those who have
worked with other ahead-of-time compilation languages are likely to
appreciate Rust’s build system and its comprehensive package
manager: cargo. At first glance, we see that cargo is a front-end for
rustc, the compiler, but cargo provides these commands for Rust
programmers:

cargo init creates a skeleton Rust project.


cargo build downloads dependencies and compiles the
code.
cargo run does the same as cargo build but also runs the
resulting executable file.
cargo doc builds HTML documentation for every
dependency in the current project.

1.6.3 Goal of Rust: Control


Control over memory access, memory layout, and specific CPU
instructions is important when squeezing the best performance out
of code. At times, it is imperative to manage how something is
operating. It might matter that data is stored in the stack rather
than on the heap. At times, it might make sense to add reference
counting to a shared value. Often, it makes sense to pass references
to functions. Occasionally, it might be useful to create one’s own
type of pointer for a particular access pattern. Most of the time
though, there are other things to worry about. And for the majority,
Rust uses sensible defaults that align with its “zero cost abstractions”
philosophy.
Note
If the terms such as stack, heap, and reference counting are
new, don’t put the book down! We’ll spend lots of time
explaining these and how they work together throughout the
rest of the book.

The following code snippet prints the line a: 10, b: 20, c: 30, d:
Mutex { data: 40 }. Each representation is another way to store an
integer. As we progress through the next few chapters, the trade-
offs related to each level become apparent. For the moment, the
important thing to remember is that the menu is comprehensive.
You are welcome to choose exactly what’s right for your specific use
case.

Listing 1.9 demonstrates multiple mechanisms for creating integer


values. Each form provides differing semantics and run-time
characteristics. But programmers retain full control of the trade-offs
that they want to make.

Listing 1.9. Multiple mechanisms for creating integer


values

use std::rc::Rc;
use std::sync::{Arc, Mutex};

fn main() {
let a = 10; ①

let b = Box::new(20); ②

let c = Rc::new(Box::new(30)); ③

let d = Arc::new(Mutex::new(40)); ④

println!("a: {:?}, b: {:?}, c: {:?}, d: {:?}", a, b, c, d);


}
① Integer on the stack
② Integer on the heap, also known as a boxed integer
③ Boxed integer wrapped within a reference counter
④ Integer wrapped in an atomic reference counter and protected by
a mutual exclusion lock

To understand why Rust is doing something the way it is, it can be


helpful to refer back to these three principles:

Data within Rust is immutable by default.


The language’s first priority is safety.
Compile-time checks are strongly preferred. Safety should
be a “zero-cost abstraction.”

[13] See the articles “We need a safer systems programming language,”
https://msrc-blog.microsoft.com/2019/07/18/we-need-a-safer-systems-
programming-language/ and “Memory safety,”
https://www.chromium.org/Home/chromium-security/memory-safety for more
information.

[14] The name "`unit” reveals some of Rust’s heritage as a descendant of the ML
family of programming languages. Theoretically, a unit type only has a single
value, itself. Compare this with Boolean types that have two values, truth or
falsehood.

[15] If these terms are unfamiliar, do keep reading. These are explained
throughout the book.

1.7 RUST’S BIG FEATURES


Our tools shape what we believe we can create. Rust enables you to
build the software that you want to make, but were too scared to
try. So what kind of tool is Rust? Flowing from the three principles
discussed in the last section are three overarching features of the
language:

Performance
Concurrency
Memory efficiency

1.7.1 Performance
Rust offers you all of your computer’s available performance.
Famously, Rust does not rely on a garbage collector to provide its
memory safety.

There is, unfortunately, a problem with promising you faster


programs: the speed of your CPU is fixed. Thus, for software to run
faster, it needs to do less. Yet, the language is large. To resolve this
conflict, Rust pushes the burden onto the compiler.

The Rust community prefers a bigger language with a compiler that


does more, rather than a simpler language where the compiler does
less. The Rust compiler aggressively optimizes both the size and
speed of your program. Rust also has some less obvious tricks:

Cache-friendly data structures are provided by default.


Arrays usually hold data within Rust programs rather than
deeply nested tree structures that are created by pointers.
This is referred to as data-oriented programming.
The availability of a modern package manager (cargo)
makes it easy to benefit from the world’s smartest
programmers. C and C++ have much less consistency
here, and building large projects with many dependencies
is typically difficult.
Methods are always dispatched statically unless you
explicitly request dynamic dispatch. This enables the
compiler to heavily optimize code, sometimes to the point
of eliminating the cost of a function call entirely.

1.7.2 Concurrency
Asking a computer to do more than one thing at the same time has
proven difficult for software engineers. As far as an operating system
is concerned, two independent threads of execution are at liberty to
destroy each other if a programmer makes a serious mistake. Yet
Rust has spawned the saying “fearless concurrency.” Its emphasis on
safety crosses the bounds of independent threads. There is no global
interpreter lock (GIL) to constrain a thread’s speed. We explore
some of the implications of this in part 2.

1.7.3 Memory efficiency


Rust enables you to create programs that require minimal memory.
When needed, you can use fixed-size structures and know exactly
how every byte is managed. High-level constructs, such as iteration
and generic types, incur minimal run-time overhead.

1.8 DOWNSIDES OF RUST


It’s easy to talk about this language as if it is the panacea for all
software engineering. For example

“A high-level syntax with low-level performance!”


“Concurrency without crashes!”
“C with perfect safety!”

These slogans (sometimes overstated) are great. But for all of its
merits, Rust does have some disadvantages.
1.8.1 Cyclic data structures
It is difficult to model cyclic data like an arbitrary graph structure in
Rust. Implementing a doubly-linked list is an undergraduate-level
computer science problem. Yet Rust’s safety checks do hamper
progress here. If you’re learning the language, avoid implementing
these sorts of data structures until you’re more familiar with Rust.

1.8.2 Compile times


Rust is slower at compiling code than its peer languages. It has a
complex compiler toolchain that receives multiple intermediate
representations and sends lots of code to the LLVM compiler. The
“unit of compilation” for a Rust program is not an individual file but a
whole package (known affectionately as a “crate”). As crates can
include multiple modules, these can be very large units to compile.
Although this enables whole-of-crate optimization, it requires whole-
of-crate compilation as well.

1.8.3 Strictness
It’s impossible—well, difficult—to be lazy when programming with
Rust. Programs won’t compile until everything is just right. The
compiler is strict, but helpful.

Over time, it’s likely that you’ll come to appreciate this feature. If
you’ve ever programmed in a dynamic language, then you may have
encountered the frustration of your program crashing because of a
misnamed variable. Rust brings that frustration forward so that your
users don’t have to experience the frustration of things crashing.
1.8.4 Size of the language
The language is large! It has a complex type system with multiple
ways to gain access to values and an ownership system that is
paired with enforced object lifetimes. The following snippet, shown
before as listing 1.9, probably causes a degree of anxiety. It’s fairly
overwhelming.

Listing 1.10. Demonstrating several ways to wrap an


integer

use std::rc::Rc;
use std::sync::{Arc, Mutex};

fn main() {
let a = 10; ①

let b = Box::new(20); ②

let c = Rc::new(Box::new(30)); ③

let d = Arc::new(Mutex::new(40)); ④

println!("a: {:?}, b: {:?}, c: {:?}, d: {:?}", a, b, c, d);


}

① Integer on the stack


② Integer on the heap, also known as a boxed integer
③ Boxed integer wrapped within a reference counter
④ Integer wrapped in an atomic reference counter and protected by
a mutual exclusion lock

The downside of allowing full control is that programmers have the


burden of choice. Exactly which integer type you should choose
depends on the problem at hand.
1.8.5 Hype
The Rust community is wary of growing too quickly and being
consumed by hype. Yet, a number of software projects have
encountered this question in their Inbox: “Have you considered
rewriting this in Rust?” Or they issue a tracker recommending a
complete rewrite in a new language.

Software written in Rust is not immune to security problems. By


2015, as Rust gained prominence, implementations of SSL/TLS
(namely, OpenSSL and Apple’s own fork) were found to have serious
security holes. Known informally as “Heartbleed” and “goto fail,”
both exploits provided opportunities to test Rust’s claims of memory
safety. Rust is likely to have helped in both cases, but it is still
possible to write Rust code that suffers from similar issues.

HEARTBLEED
Heartbleed was caused by re-using a buffer incorrectly. A buffer is a
space set aside in memory for receiving input. Data can leak from
one read to the next if the buffer’s contents are not cleared between
writes.

Why does this situation occur? Programmers hunt for performance.


Buffers are reused to minimize how often memory applications ask
for memory from the OS.

Imagine that we want to process some secret information from


multiple users. We decide, for whatever reason, to reuse a single
buffer through the course of the program. If we don’t reset this
buffer once we use it, information from earlier calls will leak to the
latter ones. Here is a précis of a program that would encounter this
error:
let buffer = &mut[0u8; 1024]; ①

read_secrets(&user1, buffer); ②
store_secrets(buffer);

read_secrets(&user2, buffer); ③
store_secrets(buffer);

① Binds a reference (&) to a mutable (mut) array ([…]) that


contains 1,024 unsigned 8-bit integers (u8) initialized to 0 to the
variable buffer.
② Fills buffer with bytes from the user1 object
③ buffer still contains data from user1 that may or may not be
overwritten by user2.

Rust does not protect you from logical errors. Rust ensures that your
data is never able to be written in two places at the same time. It
does not ensure that your program is free from all security issues.

GOTO FAIL
The “goto fail” bug is caused by programmer error coupled with C
design issues (and potentially its compiler for not pointing out the
flaw). A function that was designed to verify a cryptographic key pair
ended up skipping all checks. Here is a selected extract from the
function with a fair amount of obfuscatory syntax retained:

static OSStatus
// line break OK below? original exceeded 76 char limit
SSLVerifySignedServerKeyExchange(SSLContext *ctx, bool isRsa,
SSLBuffer signedParams,
uint8_t *signature, UInt16 signatureLen)
{
OSStatus err; ①

...

// need line break below at 55 char max (because line contains annotation)
if ((err = SSLHashSHA1.update(&hashCtx, &serverRandom)) != 0) ②
goto fail;
if ((err = SSLHashSHA1.update(&hashCtx, &signedParams)) != 0)
goto fail;
goto fail; ③
if ((err = SSLHashSHA1.final(&hashCtx, &hashOut)) != 0)
goto fail;

err = sslRawVerify(ctx,
ctx->peerPubKey,
dataToSign, /* plaintext \*/
dataToSignLen, /* plaintext length \*/
signature,
signatureLen);
if(err) {
sslErrorLog("SSLDecodeSignedServerKeyExchange: sslRawVerify "
"returned %d\n", (int)err);
goto fail;
}

fail:
SSLFreeBuffer(&signedHashes);
SSLFreeBuffer(&hashCtx);
return err; ④

① Initializes OSStatus with a pass value (e.g., 0)


② A series of defensive programming checks
③ Unconditional goto skips SSLHashSHA1.final() and the
(significant) call to sslRawVerify().
④ Returns the pass value of 0, even for inputs that should have
failed the verification test

In the example code, the issue lies between lines 12 and 14. In C,
logical tests do not require curly braces. C compilers interpret those
three lines like this:

if ((err = SSLHashSHA1.update(&hashCtx, &signedParams)) != 0) {


goto fail;
}
goto fail;

Would Rust have helped? Probably. In this specific case, Rust’s


grammar would have caught the bug. It does not allow logical tests
without curly braces. Rust also issues a warning when code is
unreachable. But that doesn’t mean the error is made impossible in
Rust. Stressed programmers under tight deadlines make mistakes.
In general, similar code would compile and run.

Tip
Code with caution.

1.9 WHERE DOES RUST FIT BEST?


Although it was designed as a systems programming language, Rust
is a general-purpose language. It has been successfully deployed in
many areas, which we discuss next.

1.9.1 Command-line utilities


Rust offers three main advantages for programmers creating
command-line utilities: minimal startup time, low memory use, and
easy deployment. Programs start their work quickly because Rust
does not need to initialize an interpreter (Python, Ruby, …) or virtual
machine (Java, C#, …).

As a bare-metal language, Rust produces memory-efficient


[16]
programs. As you’ll encounter throughout the book, many
types are zero-sized. That is, these only exist as hints to the
compiler and take up no memory at all in the running program.
Another Random Scribd Document
with Unrelated Content
March; they had had some bacon, but no soap, and the mixture of
lamp black from the pine, and grease from the bacon, had disfigured
them beyond the recognition of their own mothers. Their hair was
long and unkempt, and filled with lamp black until it was so stiff that
it stuck out like “quills of the fretful porcupine.” Their clothes were in
rags, yes in tatters. They were shoeless, hatless, and usually
coatless. They looked more like the terrible fancies of Gustave Dore
than like human beings. And yet these poor boys were originally fair-
haired, fair-skinned, blue-eyed, loyal, brave sons of fathers and
mothers who were in easy circumstances, and in many cases
wealthy; who would have shed their hearts’ last drop of blood, for
that poor boy, if it would have been of any avail. Or they were
husbands to fair women, and fathers to sweet blue-eyed children,
who were waiting for husband and papa, to come home.
Alas! those fathers and mothers, those wives and children are
waiting yet, yea and shall wait until the sea, and the graves at
Andersonville, give up their dead.
CHAPTER VII.
WINDER AND WIRZ.
“Lady Anne. Foul devil, for God’s sake hence, and trouble us not;
For thou hast made the happy earth thy hell,
Filled it with cursing cries, and deep exclaims.
If thou delight to view thy heinous deeds,
Behold this pattern of thy butcheries.”
—King Richard, III.
Shakspere.

The man who had charge of the prison at Andersonville, and who
was responsible for the barbarities practiced there, more than any
other man, was Gen. John H. Winder.
I had not the honor(?) of a personal acquaintance with that fiend in
human shape, but Comrade John McElroy of the 16 Illinois Cavalry,
the author of “Andersonville,” gives his readers a description of the
man. I quote from that work.
“There rode in among us, a few days after our arrival, an old man
whose collar bore the wreathed stars of a Major General. Heavy
white locks fell from beneath his slouched hat, nearly to shoulders.
Sunken gray eyes too dull and cold to light up, marked a hard,
stony face, the salient features of which was a thin lipped,
compressed mouth, with corners drawn down deeply—the mouth
which seems the world over to be the index of selfish, cruel, sulky
malignance. It is such a mouth as has the school boy—the coward
of the play ground, who delights in pulling off the wings of flies. It
is such a mouth as we can imagine some remorseless inquisitor to
have had—that is, not an inquisitor filled with holy zeal for what he
mistakenly thought the cause of Christ demanded, but a spleeny,
envious, rancorous shaveling, who tortured men from hatred of
their superiority to him, and sheer love of inflicting pain.
The rider was John H. Winder, Commissary General of Prisoners,
Baltimorean renegade and the malign genius to whose account
should be charged the deaths of more gallant men than the
inquisitors of the world ever slew by the less dreadful rack and
wheel. It was he who in August could point to three thousand and
eighty-one new made graves for that month, and exultingly tell his
hearer that he was “doing more for the Confederacy than twenty
regiments.”
His lineage was in accordance with his character. His father was
that General William H. Winder, whose poltroonery at Bladensburg,
in 1814 nullified the resistance of the gallant Commodore Barney,
and gave Washington to the British.
The father was a coward and incompetent; the son, always
cautiously distant from the scene of hostilities, was the tormentor
of those whom fortunes of war and the arms of brave men threw
into his hands.“
Of his personal appearance I have no recollection, but the above is a
true picture of his character. He filled a place in the Confederacy
which no brave officer of equal rank would have accepted. Hill,
Longstreet, Early, Polk, Hardee, even Forrest and Mosby would have
spurned with contempt an offer of assignment to the position
occupied by the cowardly John H. Winder.
Of Captain Henry Wirz I can write of my own knowledge. In personal
appearance he was about five feet nine or ten inches in height,
slightly built with stooping shoulders. He had a small peaked head,
small twinkling eyes, grisly, frowsy whiskers, and the general contour
of his features and expression of eyes reminded one of a rodent.
In character he was pusillanimous, vindictive, mean and irritable to
those beneath him, or who had the misfortune to be in his power;
while to his superiors he was humble and cringing, an Uriah Heep; a
person who would “Crook the pregnant hinges of his knee, that thrift
might follow fawning.”
As a specimen of the contemptible meanness of these two persons, I
was told by a prisoner who attempted to escape, but was recaptured
and put in the stocks, that while at their head-quarters he saw a
large dry-goods box nearly full of letters written by prisoners to their
friends; and by friends to them, which had accumulated, and which
they had neglected to forward or distribute. The paper upon which
some of these letters was written, and the envelope in which it was
enclosed had cost the prisoner, perhaps, his last cent of money, or
mouthful of food. The failure to receive those letters had deprived
many a mother or wife of the last chance to hear from a loved one,
or a prisoner of his last chance to hear from those he loved more
than life itself.
Wirz was Commandant of the inner prison and in this capacity, had
charge of calling the roll, organization of prisoners, issuing rations,
the sanitary condition of the prison, the punishment of prisoners; in
fact the complete control of the inner prison.
Winder had control of all the guards, could control the amount of
rations to be issued, make the rules and regulations of the prison,
and had, in fact, complete control of the whole economy of the
prison; all men and officers connected therewith being subordinate
to him.
Wirz’ favorite punishment for infringement of prison rules, was the
chain-gang, and stocks. Sometimes twelve or fifteen men were
fastened together by shackles attached to a long chain. These
unfortunate men were left to broil in a semi-tropical sun, or left to
shiver in the dews and pelting rains, without shelter as long as Wirz’
caprice or malignity lasted. The stocks were usually for punishment
of the more flagrant offenses, or when Wirz was in his worst humor.
Just below my tent, two members of a New York regiment put up a
little shelter. They always lay in their tent during the day, but at
night one might see a few men marching away from their “shack”
carrying haversacks full of dirt, and emptying them along the edge
of the swamp. One morning the tent was gone, and a hole in the
ground marked the spot, and told the tale of their route, which was
underground through a tunnel. About 8 o’clock in the morning Wirz
came in accompanied by a squad of soldiers, and a gang of negroes
armed with shovels, who began to dig up the tunnel. I went to Wirz
and asked him what was up. He was always ready to “blow” when
he thought he could scare anybody, so he replied, “By Gott, tem
tamned Yanks has got oudt alrety, but nefer mints, I prings tem pack
all derights; I haf sent te ploothounts after dem. I tell you vat I
does, I gifs any Yank swoluf hours de shtart, undt oaf he gits avay,
all deright; put oaf I catches him I gif him hell.” Some one offered to
take the chances. “Allderights.” said he, “you come to de nort cate in
der mornick undt I lets you co.”
The next day we heard that the blood-hounds had found the trail of
the escaped prisoners, but that all but one had been foiled by
cayenne pepper, and that one, was found dead with a bullet hole in
his head. We never heard from our New York friends and infer that
that they got to “God’s Country.”
Many attempts were made to tunnel out that summer, but so far as I
know that was the only successful one. All sorts of ways were
resorted to, the favorite way being to start a well and dig down ten
or twelve feet, then start a tunnel in it near the surface of the
ground. By this means the fresh dirt would be accounted for, as well
digging was within the limits of the prison rules. But before the
“gopher-hole,” as the tunnels were called by the western boys, was
far advanced, a gang of negroes appeared upon the scene and dug
it up. We always believed there were spies among us. Some thought
the spies were some of our own men who were playing traitor to
curry favor with Wirz. Others believed Wirz kept rebel spies among
us. I incline to the former opinion.
Among those who were suspected was a one-legged soldier named
Hubbard. He hailed from Chicago and was a perfect pest. He was
quarrelsome and impudent and would say things that a sound man
would have got a broken head for saying. His squawking querulous
tones, and hooked nose secured for him the name of “Poll Parrott.”
He was a sort of privileged character, being allowed to go outside,
which caused many to believe he was in league with Wirz, though I
believe there was no direct proof of it. One day he came to where I
was cooking my grub and wanted me to take him in. He said all his
comrades were down on him and called him a spy, and he could not
stand it with them. As a further inducement he said he could go out
when he had a mind, and get wood and extra rations, which he
would divide with me. I consulted my “pard” and we agreed to take
him in. He then asked me to cook him some dinner, and gave me his
frying-pan and some meat. While I was cooking his dinner he
commenced finding fault with me, upon which I suggested that he
had better do his own cooking. He then showered upon my devoted
head some of the choicest epithets found in the Billingsgate dialect,
he raved and swore like a mad-man. I was pretty good natured
naturally, and besides I pitied the poor unfortunate fellow, but this
presuming on my good nature a little too much, I fired his frying-pan
at his head and told him to “get”; and he “got.”
Two days afterwards he went under the Dead-line and began to
abuse the guard, a member of an Alabama regiment, who ordered
him to go back, or he would shoot him. “Poll” then opened on the
guard in about the same style as he had on me, winding up by
daring the guard to fire. This was too much and the guard fired a
plunging shot, the ball striking him in the chin and passing down into
his body, killing him instantly.
A few days before this, a “fresh fish,” or “tender foot,” as the cow
boys would call him nowadays, started to cross the swamp south of
my tent. In one place in the softest part of the swamp the railing
which composed the Dead-line was gone, this man stepped over
where the line should have been, and the guard fired at him but he
fired too high and missed his mark, but the bullet struck an Ohio
man who was sitting in front of a tent near mine. He was badly, but
not fatally wounded, but died in a few days from the effects of
gangrene in his wound.
The author of “Andersonville” makes a wide distinction between the
members of the 29th Alabama and the 55th Georgia regiments,
which guarded us, in relation to treatment of prisoners, claiming that
Alabama troops were more humane than the Georgia “crackers.”
This was undoubtedly true in this instance, but I am of the opinion
that state lines had nothing to do with the matter.
The 29th Alabama was an old regiment and had been to the front
and seen war, had fired at Yankees, and had been fired at by
Yankees in return; they had no need to shoot defenseless prisoners
in order to establish the enviable reputation of having killed a
“damned Yank;” while the 55th Georgia was a new regiment, or at
least one which had not faced the music of bullets and shells on the
field of battle, they had a reputation to make yet, and they made
one as guards at Andersonville, but the devil himself would not be
proud of it, while the 5th Georgia Home Guards, another regiment of
guards, was worse than the 55th.
In making up the 5th Geo. H. G. the officers had “robbed the cradle
and the grave,” as one of my comrades facetiously remarked.
Old men with long white locks and beards, with palsied, trembling
limbs, vied with boys, who could not look into the muzzles of their
guns when they stood on the ground, who were just out of the
sugar pap and swaddling clothes period of their existence, in killing a
Yank. It was currently reported that they received a thirty days
furlough for every prisoner they shot; besides the distinguished
“honah.”
In marked contrast with these two Georgia regiments was the 5th
Georgia regulars. This regiment guarded us at Charleston, S. C., the
following September, and during our three weeks stay at that place I
have no recollection of the guards firing on us, although we were
camped in an open field with nothing to prevent our escape but
sickness, starvation, and a thin line of guards of the 5th Ga.
regulars. But this regiment too had seen service at the front. They
had been on the Perryville Campaign, had stood opposed to my
regiment at the battle of Perryville and had received the
concentrated volleys of Simonson’s battery and the 10th Wisconsin
Infantry, and in return had placed 146 of my comrades HORS DE
COMBAT. They had fought at Murfresboro and Chickamauga, at
Lookout and Missionary Ridge and had seen grim visaged war in
front of Sherman’s steadily advancing columns in the Atlanta
campaign. Surely they had secured a record without needlessly
shooting helpless prisoners.
I believe all ex-prisoners will agree with me, that FIGHTING regiments
furnished humane guards.
For the purpose of tracking escaped prisoners, an aggregate of
seventy blood-hounds were kept at Andersonville. They were run in
packs of five or six, unless a number of prisoners had escaped, in
which case a larger number were used. They were in charge of a
genuine “nigger driver” whose delight it was to follow their loud
baying, as they tracked fugitive negroes, or escaped Yanks through
the forests and swamps of southern Georgia.
These blood-hounds were trained to track human beings, and with
their keen scent they held to the track as steadily, relentlessly as
death itself; and woe betide the fugitive when overtaken, they tore
and lacerated him with the blood-thirsty fierceness of a Numidian
lion.
These willing beasts and more willing guards were efficient factors in
the hands of Winder and Wirz in keeping in subjection the prisoners
entrusted to their care. But these are outside forces. Within the
wooden walls of that prison were more subtile and enervating forces
at work than Georgia militia or fierce blood-hound.
Diarrhea, scurvy and its concomitant, gangrene, the result of
insufficient and unsuitable food and the crowded and filthy state of
the prison, were doing their deadly work, swiftly, surely and
relentlessly.
CHAPTER VIII.

“Ghost. I could a tale unfold, whose lightest word


Would harrow up thy soul; freeze thy young blood;
Make thy two eyes, like stars, start from their spheres;
Thy knotted and combined locks to part,
And each particular hair to stand on end,
Like quills upon the fretful porcupine.”
—Hamlet.

The cook-house, which I have already spoken of, had a capacity for
cooking rations for 10,000 men. Our rations consisted, during the
latter part of April and through May, of about a pound of corn bread,
of about the same quality as that at Danville, a piece of meat about
the size of two fingers, and a little salt per day. This was varied by
issuing rice or cow peas in the place of meat, but meat and rice, or
peas, were never issued together. We had no more bug soup, nor
soup of any kind from the cook-house. We got our bugs in the peas,
so that we were not entirely destitute of meat when we had peas.
The rice was filled with weevil, so that that too, was stronger, if not
more nutritious. But when our numbers were increased by the
prisoners who had been captured at Dalton, Resaca, Alatoona, New
Hope Church and Kenesaw, from Sherman’s army, and from the
Wilderness, from Meade’s army, our numbers had far outgrown the
capacity of the cook-house and our rations were issued to us raw.
Then commenced real, downright misery and suffering. These men
were turned into the prison after being robbed of everything of
value, without shelter, without cooking utensils, without wood,
except in the most meager quantities, and in most cases without
blankets.
Raw meal, raw rice and peas, and no dish to cook them in, and no
wood to cook them with, and yet there were thousands of acres of
timber in sight of the prison, and these men would have been too
glad to cut their own wood and bring it into the prison on their
shoulders. But this would have been a luxury, and Winder did not
furnish prisoners with luxuries. There was an abortive attempt made
at cooking more rations, by cooking them less, and the result was,
meal simply scalded and called “mush,” and rice not half cooked,
and burned black wherever it touched the kettle it was boiled in.
The effects of this unwholesome, half cooked, and in thousands of
cases raw diet, was an increase of diarrhea, and dysentery, and
scurvy.
In thousands of cases of scurvy where scorbutic ulcers had broken
out, gangrene supervened and the poor prisoner soon found
surcease of pain, and misery, and starvation, in the grave.
Amputation of a limb was not a cure for these cases; new scorbutic
ulcers appeared, again gangrene supervened, and death was the
almost inevitable result.
The prison was filled with sick and dying men, indeed well men were
the exception, and sick men the rule. The hospital was filled to
overflowing; the prison itself, was a vast hospital, with no physicians,
and no nurses.
Thousands of men had become too sick and weak to go to the sinks
to stool, and they voided their excrement in little holes dug near
their tents. The result of this was, a prison covered with maggots,
and the air so polluted with the foul stench, that it created an
artificial atmosphere, which excluded malaria, and in a country
peculiarly adapted to malarial diseases, there were no cases of
Malarial, Typhus or Typhoid fevers.
Your true Yankee is an ingenious fellow, and is always trying to
better his situation. Many cooking dishes were manufactured by the
prisoners out of tin cans, pieces of sheet iron, or car roofing, which
had been picked up on the road to prison.
Knives and spoons were made from pieces of hoop iron, and a
superannuated oyster or fruit can, was a whole cooking
establishment, while a tin pail or coffee pot caused its owner to be
looked upon as a nabob.
Fortunately for myself I was joint owner with six men of my
company, of a six quart tin pail. This we loaned at times to the more
unfortunate, thus helping them somewhat in their misery. Besides
this mine of wealth, I had an interest in the wooden bucket
purloined from the Danville prison, and as Sergeant of the mess, it
was in my care. To this bucket I owe, in a great measure, my life;
for I used it for a bath tub during my confinement in Andersonville.
Another cause of suffering was the extreme scarcity of water. When
the Richmond and Belle Isle prisoners arrived in Andersonville in
February and March, they had procured their water from Dead-run;
but by the time our squad arrived this little stream had become so
polluted that it was not fit for the wallowing place of a hog.
Our first work after building a shelter was to procure water. We first
dug a hole in the edge of the swamp, but this soon became too
warm and filthy for use, so we started a well in an open space in
front of my tent, and close to the Dead-line. We found water at a
depth of six feet, but it was in quicksand and we thought our well
was a failure; but again luck was on our side. One of the prisoners
near us, had got hold of a piece of board while marching from the
cars to the prison, this he offered to give us in exchange for stock in
our well.
We completed the bargain, and with our Danville sawknife cut up
the board into water-curbing, which we sank into the quicksand,
thus completing a well which furnished more water than any well in
the whole prison.
To the credit of my mess, who owned all the right, title and interest,
in and to this well, I will say, we never turned a man away thirsty.
After we had supplied ourselves, we gave all the water the well
would furnish to the more unfortunate prisoners who lived on the
hill, and who could procure no water elsewhere.
After we had demonstrated the fact that clean water could be
procured even in Andersonville, a perfect mania for well digging
prevailed in prison; wells were started all over, but the most of them
proved failures for different reasons, some were discouraged at the
great depth, others had no boards for water-curbing, and their wells
caved in, and were a failure. There were, however, some wells dug
on the hill, to a depth of thirty or forty feet. They furnished water of
a good quality, but the quantity was very limited.
The digging of these deep wells was proof of the ingenuity and
daring of the prisoners. The only digging tool was a half canteen,
procured by unsoldering a canteen. The dirt was drawn up in a
haversack, or bucket, attached to a rope twisted out of rags, from
the lining of coat sleeves or strips of shelter tents. The well diggers
were lowered into, and drawn out of, the wells by means of these
slight, rotten ropes, and yet, I never heard of an accident as a result
of this work.
But the wells were not capable of supplying one-fourth of the men
with water. Those who had no interest in a well, and could not beg
water from those who had, were compelled to go to Dead-run for a
supply.
A bridge crossed this stream on the west side of the prison, and
here the water was not quite so filthy as farther down stream. This
bridge was the slaughter pen of the 55th Georgians, and the 5th
Georgia Home Guards.
Here the prisoners would reach under the Dead-line to procure clean
water, and the crack of a Georgian’s musket, was the prisoner’s
death knell.
During the early part of August Providence furnished what Winder
and Wirz refused to furnish. After a terrible rain storm, a spring
broke out under the walls of the stockade about ten or fifteen rods
north of this bridge. Boards were furnished, out of which a trough
was made which carried the water into the prison. The water was of
good quality, and of sufficient quantity to have supplied the
prisoners, could it have been saved by means of a tank or reservoir.
This was the historical “Providence Spring” known and worshiped by
all ex-Andersonville prisoners.
The same rain storm which caused Providence Spring to break out,
gullied and washed out the ground between our well and the
stockade to a depth of four feet, and so saturated the ground that
the well caved in. We were a sad squad of men, as we gathered
around the hole where our hopes of life were buried, for without
pure water, we knew we could not survive long in Andersonville.
Two days after the accident to our well, we held a legislative session,
and resolved ourselves into a committee of the whole, on ways and
means to restore our treasure. No one could think of any way to fix
up the well, boards were out of the question, stones there were
none, and barrels:—we had not seen a barrel since we left “God’s
Country.” As chairman, ex-officio, of the committee, I proposed that
we steal a board from the Dead-line. This was voted down by the
committee as soon as proposed, the principle was all right, but the
risk was too great; death would be the penalty for the act. The
committee then rose and the session was adjourned. After
considering the matter for a time, I resolved to steal a board from
the Dead-line at any risk. I then proceeded to mature a plan which I
soon put into execution. One of my “pards,” Rouse, had a good silver
watch, I told him to go up to the Dead-line in front of the first guard
north of our tent, and show his watch, and talk watch trade with the
guard. I sent Ole Gilbert, my other pard, to the first guard south,
with the same instructions, but minus a watch. I kept my eyes on
the guards and watched results; soon I saw that my plan was
working. I picked up a stick of wood and going to a post of the
Dead-line, where one end of a board was nailed, I pried off the end
of the board, but O horror! how it squealed, it was fastened to a
pitch pine post with a twelve penny nail and when I pried it loose, it
squeaked like a horse fiddle at a charivari party. I made a sudden
dive for my tent, which was about sixteen feet away, and when I
had got under cover I looked out to see the result. The guards were
peering around to see what was up, their quick ears had caught the
sound, but their dull brain could not account for the cause.
After waiting until the guards had become again interested in the
mercantile transaction under consideration, I crawled out of my tent
and as stealthily as a panther crawled to my board again. This time I
caught it at the loose end, and with one mighty effort I wrenched it
from the remaining posts, dropped it on the ground, and again dove
into my tent.
The guards were aroused, but not soon enough to see what had
been done, and I had secured a board twenty feet long by four
inches wide, lumber enough to curb our well.
Another meeting of the mess was held, the saw-knife was brought
out, the board, after great labor, was sawed up, and our well was
restored to its usefulness.
This same storm, which occurred on the 12th of August, was the
cause of a quite an episode in our otherwise dull life in prison. It was
one of those terrible rains which occur sometimes in that region, and
had the appearance of a cloud-burst. The rain fell in sheets, the
ground in the prison was completely washed, and much good was
done in the way of purifying this foul hole. The rapid rush of water
down the opposing hills, filled the little stream, which I have called
Dead-run, to overflowing, and as there was not sufficient outlet
through the stockade, for the fast accumulating water, the pressure
became so great that about twenty feet of the stockade toppled and
fell over.
Thousands of prisoners were out looking at the downfall of our
prison walls and when it went over we sent up such a shout and
hurrah that we made old Andersonville ring.
But the rebel guard had witnessed the break as well as we. The
guard near the creek called out “copeler of the gyaad! post numbah
fo’teen! hurry up, the stockade is goin to h—l.” The guards, about
3,000 in number, came hurrying to the scene and formed line of
battle to prevent a rush of prisoners, while the cannoneers in the
forts sprang to their guns. We saw them ram home the charges in
their guns, then we gave another shout, when BANG went one of the
guns from the south-western fort, and we heard a solid shot go
shrieking over our heads. It began to look as though the Johnies
were going to get the most fun out of this thing after all. Just at this
time Wirz came up to the gap and shrieked, “co pack to your
quarters, you tammed Yanks, or I vill open de cuns of de forts on
you.”
I needed no second invitation after that shot went over our heads,
and I hurried to my quarters and laid low. I don’t think I am
naturally more cowardly than the average of men, but that shot
made me tired. I was sick and weak and had no courage, and knew
Winder and Wirz so well that I had perfect faith that they would be
only too glad of an excuse to carry out the threat.
But let us go back to the month of May. Soon after my arrival, there
was marched into the prison about two thousand of the finest
dressed soldiers I ever saw. Their uniforms were new and of a better
quality than we had ever seen in the western army. They wore on
their heads cocked hats, with brass and feather accompaniments.
Their feet were shod with the best boots and shoes we had seen
since antebellum days, their shirts were of the best “lady’s cloth”
variety, and the chevrons on the sleeves of the non-commissioned
officers coats, were showy enough for members of the Queen’s
Guards.
Poor fellows, how I pitied them. The mingled look of surprise, horror,
disgust, and sorrow that was depicted on their faces as they
marched between crowds of prisoners who had been unwilling
guests of the Confederacy for, from four to nine months, told but too
plainly how our appearance affected them. As they passed along the
mass of ragged, ghastly, dirt begrimed prisoners, I could hear the
remark, “My God! have I got to come to this?” “I can’t live here a
month,” “I had rather die, than to live in such a place as this,” and
similar expressions. I say that I pitied them, for I knew that the sight
of such specimens of humanity as we were, had completely
unnerved them, that their blood had been chilled with horror at sight
of us, and that they would never recover from the shock; and they
never did.
Yes they had to come to this; many of them did not live a month,
and not many of those two thousand fine looking men ever lived to
see “God’s Country” again.
These were the “Plymouth Pilgrims.” They were a brigade, composed
of the 85th New York, the 101st and 103d Pennsylvania, 16th
Connecticut, 24th New York Battery, two companies of
Massachusetts heavy artillery and a company of the 12th New York
cavalry.
They were the garrison of a fort at Plymouth, North Carolina, which
had been compelled to surrender, on account of the combined attack
of land and naval forces, on the 20th day of May, 1864.
Some of the regiments composing this band of Pilgrims had
“veteranized” and were soon going home on a veteran furlough
when the attack was made, but they came to Andersonville instead.
Their service had been most entirely in garrisons, where they had
always been well supplied with rations and clothing, and exempt
from hard marches and exposures, and as a natural sequence, were
not as well fitted to endure the hardships of prison life, as soldiers
who had seen more active service.
They were turned into the prison without shelter, and they did not
seem to think they could, in any way, provide one; without cooking
utensils, and they thought they must eat their food raw. They began
to die off in a few days after their arrival, they seemed never to have
recovered from their first shock.
Comrade McElroy tells in “Andersonville,” a pathetic story of a
Pennsylvanian who went crazy from the effects of confinement. He
had a picture of his wife and children and he used to sit hour after
hour looking at them, and sometimes imagined he was with them
serving them at the home table. He would, in his imagination, pass
food to wife and children, calling each by name, and urging them to
eat more. He died in a month after his entrance.
I observed a similar case near my quarters. One of this same band
came to our well for a drink of water which we gave him. He was
well dressed, at first, but seemed to be a simple-minded man. Day
after day he came for water, sometimes many times a day. Soon he
began to talk incoherently, then to mutter something about home
and food. One day his hat was gone; the next day his boots were
missing, and so on, day after day, until he was perfectly nude,
wandering about in the hot sun, by day, and shivering in the cold
dews at night, until at last we found him one morning lying in a ditch
at the edge of the swamp,—dead.
God only knows how many of those poor fellows were chilled in
heart and brain, at their first introduction to Andersonville.
The coming of the Pilgrims into prison was the beginning of a new
era in its history. Before they came, there was no money among the
prisoners, or so little as to amount to nothing; but at the time of
their surrender they had been paid off, and those who had
“veteranized” had been paid a veteran bounty, so that they brought
a large sum of money into prison.
The reader may inquire how it was that they were not searched, and
their money and valuables taken from them by Winder and Wirz? It
is a natural inquiry, as it was the only instance in the record of
Andersonville, so far as I ever heard, when such rich plunder
escaped those commissioned robbers. The reason they escaped
robbery of all their money, clothing, blankets and good boots and
shoes, was, they had surrendered with the agreement that they
should be allowed to keep all their personal belongings, and in this
instance the Confederate authorities had kept their agreement.
Thus several thousand dollars were brought into prison, and the old
prisoners were eager to get a share. All sorts of gambling devices
were used, the favorite being the old army Chuc-a-luck board. When
these men came in, the old prisoners had preempted all the vacant
land adjoining their quarters, and they sold their right to it, to these
tender-feet for large sums, for the purpose of putting up shelters on.
This they had no right to do, but the Pilgrims did not know it.
As the money began to circulate, trade began to flourish. Sutler, and
soup stands sprung up all over the prison, where vegetables and
soup were sold at rates that would seem exorbitant in any other
place than the Confederacy. The result of all this gambling and
trading, together with another cause which I will mention, was, that
the Pilgrims were soon relieved of all their money, and then began to
trade their clothing. Thus these well supplied, well dressed prisoners
were soon reduced to a level with the older prisoners; but there was
a compensation in this, as well as in nature, for what the former lost
the latter gained and they were the better off by that much.
The supplies of vegetables and food which were sold by the sutlers
and restaurateurs, were procured of the guards at the gate, they
purchasing of the “Crackers” in the vicinity, causing a lively trade to
flourish, not only in prison, but with the surrounding country.
CHAPTER IX.
THE RAIDERS.
“There must be government in all society—
Bees have their Queen, and stag herds have their leader;
Rome had her Consuls, Athens had her Archons,
And we, sir, have our Managing Committee.”

In the southern portion of the prison, bordering the swamp, there


was domiciled the worst specimens of humanity I ever knew. An
acquaintance with them would almost convince any thinking man
that there was something in Darwin’s theory of the developement of
species. If that theory is tenable, then I should argue these men had
been developed from hyenas, and not very far, or well developed
either. They wore the outward semblance of men, but retained the
cowardly, blood-thirsty, sneaking, thievish nature of the hyena.
These were the Andersonville “Raiders;” and a worse set of men
never lived,—in America, at least.
These men were from the slums of New York City and Brooklyn. I
never knew what their record as soldiers was, but as prisoners they
were the terror of all decent men. They congregated together, were
organized into semi-military organization, had their officers from
captains down, and in squads made their raids upon the peaceable
prisoners, who were possessed of anything which excited their
cupidity.
The Plymouth Pilgrims furnished a rich harvest for these miscreants,
who spotted them, marking their sleeping places, and in the dead
hour of the night robbed them of whatever they possessed; or if any
of the Pilgrims ventured into their haunts by day, they were knocked
down and robbed by daylight.
While the raiders were constantly at war with others, they were not
always at peace among themselves. Their favorite weapon with
others was a stick; but they settled their difficulties of a domestic
character with their fists.
Sometimes one of the small fry among these Raiders, would venture
out on his own hook, and pilfer any little article he could find in a
sick man’s tent. One day a member of my mess caught one of these
fellows stealing a tin cup from a sick man; he immediately gave
chase and caught him, then we held a drumhead court martial and
sentenced him to have his head shaved.
Now I do not suppose there was a razor among the thirty-three
thousand men that were in Andersonville at the time;
notwithstanding this drawback, the sentence of the court was
carried out with a pocket knife. It made the fellow scowl some, but
the executioner managed to saw his hair off after a fashion.
Another of these Raiders got his just punishment while trying to rob
a half-breed Indian, a member of the Massachusetts Heavy Artillery.
The raider attempted to steal the Indian’s boots from under his
head, when the descendant of King Phillip plunged a knife into the
hoodlum, killing him dead on the spot.
A number of murders had been committed by these Raiders, and
robberies innumerable, when matters were brought to a focus one
day in the early part of July, by Lieutenant Davis, then in command
of the Prison vice Wirz who was sick, declaring that no more rations
would be issued until these men were given up.
He had no need to threaten us;—we were willing to give them up;—
we had no earthly use for them. Give them up? yes; and pay boot,
to get rid of them. But it required a man of nerve to lead in the
arrest of these desperadoes. It was no child’s play, as there were
between four and five hundred of them, and to arrest the leaders
meant “business.” That man was found in the person of Sergeant
Leroy L. Key, of the 16th Illinois Cavalry, who was ably seconded by
a tall, lithe, young fellow known as “Limber Jim,” a member of the
67th Illinois.
To the efforts of these two men, the prisoners at Andersonville were
indebted, more than any other men, for the comparative peace and
security of the prison after the 11th of July.
Key was the head, and furnished the brains, of the organization
known, at first, as the “Regulators,” afterward as the “Prison Police.”
Limber Jim was second in command, and first in a fight.
These two men organized a force of men in the southwest corner of
the stockade, from the best material which could be found. It
needed strong brave men for the work in hand; for these Raiders
were strong, athletic men, and desperate characters, and the
Regulators must need face the lion in his den.
On the 3d of July Key at the head of the Regulators, armed with
clubs, made a charge on the Raiders, who had been expecting the
attack and were prepared. I was standing on the north side of the
swamp, and was in good position to see the fight.
Key, followed by Limber Jim, led the charge; for a few minutes the
spectators could tell nothing of how the Regulators were faring. The
air was filled with clubs, which were descending on men’s heads,
shoulders and arms. The fighting mass surged, and swayed, and
finally the Raiders broke and ran; and then the spectators set up
such a shout as must have cheered Key and his brave men.
That day and the next, the Regulators arrested one hundred and
twenty-five of the worst characters among the Raiders. Davis gave
Key the use of the small stockade at the north gate, as a prison in
which to hold them for trial.
He then organized a Court Martial, consisting of thirteen sergeants,
selected from among the latest arrivals, in order to guard against
bias. The trial was conducted as fairly as was possible, considering
their ignorance of law. Technicalities counted for naught, facts, well
attested, influenced that court.
The trial resulted in finding six men guilty of murder; and the
sentence was hanging.
The names of the six condemned men were, John Sarsfield, William
Collins, alias “Mosby,” Charles Curtis, Patrick Delaney, A. Muir and
Terrence Sullivan.
These men were heavily ironed, and closely guarded, while the
remaining one hundred and nineteen were returned to the prison,
and compelled to run a gauntlet of men armed with clubs and fists,
who belabored them unmercifully, as they were passed through one
by one.
The sentence of the court martial was executed on these six men on
the 11th of July. A gallows was erected in the street leading from the
south gate, and the culprits marched in under a Confederate guard,
to a hollow square which surrounded the scaffold, and was formed
by Key’s brave Regulators, where they were turned over to Limber
Jim.
These desperadoes were terribly surprised when they found they
were to be hung. They imagined the court martial was a farce,
intended to scare them. Imagine their disappointment when they
were marched to the gallows, and turned over to the cool, but
resolute and firm Key, and the fiery Limber Jim, whose brother had
been murdered by one of the number. They found that it was no
farce but real genuine tragedy, in which they were to act an
important part.
When they realized this, they began to beg for mercy, but they had
shown no mercy, and now they were to receive no mercy. They then
called upon the priest, who attended them, to speak in their behalf;
but the prisoners would have none of it, but called out “hang them.”
When they found there was no mercy in that crowd of men whom
they had maltreated and robbed, and whose comrades and friends
they had murdered, they resigned themselves to their fate; all but
Curtis who broke from the guard of Regulators and ran through the
crowd, over tents, and across Dead-run into the swamp where he
was recaptured and taken back.
They were then placed upon the platform, their arms pinioned, meal
sacks were tied over their heads, the ropes adjusted around their
necks, and, at a signal given by Key, the trap was sprung and they
were launched into eternity, all but Mosby, who being a heavy man
broke his rope. He begged for his life, but it was of no avail. Limber
Jim caught him around the waist and passed him up to another
man; again the noose was adjusted and he, too, received his reward
for evil doing.
The execution of these men was witnessed by all the prisoners who
were able to get out of their tents, and it is needless to add, was
approved by them, all except the Raiders. Besides the prisoners, all
the rebels who were on duty outside, found a position where they
could witness the scene. The Confederate officers, apprehensive of a
stampede of the prisoners, took the precaution to keep their men
under arms, and the guns in the forts were loaded, the fuses
inserted in the vents and No. 4 stood with lanyard in hand ready to
suppress an outbreak.
The hanging of these men had a very salutary effect upon the other
evil doers in the prison.
Heretofore we had had no organization; we were a mob of thirty-
three thousand men, without law, and without officers. Each mess
had its own laws and each man punished those who had offended
him; that is, if he could. But now this band of thugs was broken up
and their leaders hanged. The Regulators were turned into a police
force, with the gallant Limber Jim as chief, and henceforth order
prevailed among the prisoners at Andersonville.
The reader will readily see, from reading what I have written in this
chapter, that our sufferings did not all proceed from the rebels.
Almost twenty-five years have elapsed since those scenes were
enacted, the hot passion engendered by the cruelties of prison life,
have measurably cooled, and as I am writing this story, I am
determined to “hew to the line let the chips fall where they will,” and
with a full understanding of what I say, I affirm that many of the
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebooknice.com

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy