Professional Documents
Culture Documents
PDF The Complete Rust Programming Reference Guide Rahul Sharma Ebook Full Chapter
PDF The Complete Rust Programming Reference Guide Rahul Sharma Ebook Full Chapter
https://textbookfull.com/product/mastering-delphi-programming-a-
complete-reference-guide-primoz-gabrijelcic/
https://textbookfull.com/product/the-rust-programming-language-
covers-rust-2018-steve-klabnik/
https://textbookfull.com/product/the-rust-programming-
language-1st-edition-steve-klabnik/
https://textbookfull.com/product/the-rust-programming-
language-2nd-edition-steve-klabnik/
Programming Rust 1st Edition Jim Blandy
https://textbookfull.com/product/programming-rust-1st-edition-
jim-blandy/
https://textbookfull.com/product/environmental-issues-of-deep-
sea-mining-impacts-consequences-and-policy-perspectives-rahul-
sharma/
https://textbookfull.com/product/programming-rust-fast-safe-
systems-development-jim-blandy/
https://textbookfull.com/product/programming-webassembly-with-
rust-1st-edition-kevin-hoffman/
https://textbookfull.com/product/programming-rust-2nd-edition-
early-release-jim-blandy/
The Complete Rust Programming Reference Guide
Rahul Sharma
Vesa Kaihlavirta
Claus Matzinger
BIRMINGHAM - MUMBAI
The Complete Rust
Programming Reference
Guide
Every effort has been made in the preparation of this book to ensure
the accuracy of the information presented. However, the information
contained in this book is sold without warranty, either express or
implied. Neither the authors, nor Packt Publishing or its dealers and
distributors, will be held liable for any damages caused or alleged to
have been caused directly or indirectly by this book.
ISBN 978-1-83882-810-3
www.packtpub.com
mapt.io
Mapt is an online digital library that gives you full access to over
5,000 books and videos, as well as industry leading tools to help you
plan your personal development and advance your career. For more
information, please visit our website.
Why subscribe?
Spend less time learning and more time coding with practical
eBooks and Videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
developers and tech professionals, just like you, to help them share
their insight with the global tech community. You can make a
general application, apply for a specific hot topic that we are
recruiting an author for, or submit your own idea.
Table of Contents
Title Page
Copyright
About Packt
Why subscribe?
Packt.com
Contributors
Preface
Who this book is for
Conventions used
Get in touch
Reviews
Using rustup.rs
Primitive types
Closures
Strings
Match expressions
Loops
User-defined types
Structs
Enums
Collections
Arrays
Tuples
Vectors
Hashmaps
Slices
Iterators
Summary
Package managers
Modules
Nested modules
File as a module
Directory as module
Cargo workspace
Extending Cargo and tools
cargo-edit
cargo-deb
cargo-outdated
Linting code with clippy
Organizing tests
Testing primitives
Attributes
Assertion macros
Unit tests
First unit test
Running tests
Isolating test code
Failing tests
Ignoring tests
Integration tests
First integration test
Writing documentation
Generating and viewing documentation
Hosting documentation
Doc attributes
Documentation tests
Benchmarks
Summary
4. Types, Generics, and Traits
Generic types
Generic implementations
Using generics
Abstracting behavior with traits
Traits
The many forms of traits
Marker traits
Simple traits
Generic traits
Memory safety
Trifecta of memory safety
Ownership
A brief on scopes
Ownership in action
Borrowing
Borrowing rules
Borrowing in action
Lifetime subtyping
Specifying lifetime bounds on generic types
Pointer types in Rust
References – safe pointers
Raw pointers
Smart pointers
Drop
Deref and DerefMut
Interior mutability
Cell<T>
RefCell<T>
Uses of interior mutability
Summary
6. Error Handling
Error handling prelude
Recoverable errors
Option
Result
Combinators on Option/Result
Common combinators
Using combinators
Converting between Option and Result
Early returns and the ? operator
Non-recoverable errors
User-friendly panics
Custom errors and the Error trait
Summary
7. Advanced Concepts
Joining strings
When to use &str versus String ?
Global values
Constants
Statics
Compile time functions – const fn
Dynamic statics using the lazy_static! macro
Iterators
Fn closures
FnMut closures
FnOnce closures
Consts in structs, enums, and traits
Re-exports
Selective privacy
Advanced match patterns and guards
Match guards
8. Concurrency
Approaches to concurrency
Kernel-based
User-level
Pitfalls
Concurrency in Rust
Thread basics
Customizing threads
Accessing data from threads
RwLock
Communicating through message passing
Asynchronous channels
Synchronous channels
thread-safety in Rust
What is thread-safety?
Traits for thread-safety
Send
Sync
Concurrency using the actor model
Other crates
Summary
What is metaprogramming?
When to use and not use Rust macros
Types of macros
Creating your first macro with macro_rules!
Repetitions in macros
Exercises
Procedural macros
Derive macros
Debugging macros
Useful procedural macro crates
Summary
10. Unsafe Rust and Foreign Function Interfaces
Summary
11. Logging
What is logging and why do we need it?
Unstructured logging
Structured logging
Logging in Rust
log4rs
Mio
Futures
Tokio
Building an asynchronous redis server
Summary
Web frameworks
Actix-web basics
Summary
14. Lists, Lists, and More Lists
Linked lists
A transaction log
Adding entries
Log replay
After use
Wrap up
Upsides
Downsides
Reverse
Wrap up
Upsides
Downsides
Skip lists
The list
Adding data
Leveling up
Jumping around
Upsides
Downsides
Dynamic arrays
Favorite transactions
Internal arrays
Quick access
Wrap up
Upsides
Downsides
Summary
Further reading
Upsides
Downsides
Red-black tree
Upsides
Downsides
Heaps
A huge inbox
Getting messages in
Wrap up
Upsides
Downsides
Trie
More realistic IoT device management
Adding paths
Walking
Wrap up
Upsides
Downsides
B-Tree
An IoT database
Adding stuff
Wrap up
Upsides
Downsides
Graphs
Wrap up
Upsides
Downsides
Summary
Hashing
Create your own
Message digestion
Wrap up
Maps
A location cache
The hash function
Adding locations
Fetching locations
Wrap up
Upsides
Downsides
Sets
Union
Intersection
Difference
Wrap up
Upsides
Downsides
Summary
Further reading
Sequences
Vec<T> and VecDeque<T>
Architecture
Insert
Look up
Remove
LinkedList<T>
Architecture
Insert
Look up
Remove
Wrap up
Maps and sets
Insert
Lookup
Remove
Architecture
Insert
Look up
Remove
Wrap up
Summary
Further reading
Loops
Recursion
Complexity classes
O(1)
O(log(n))
O(n)
O(n log(n))
O(n²)
O(2n)
Comparison
In the wild
Data structures
Everyday things
Exotic things
Summary
Further reading
Shell sort
Heap sort
Merge sort
Quicksort
Summary
Further reading
Linear searches
Jump search
Binary searching
Wrap up
Summary
Further reading
LCG
Wichmann-Hill
The rand crate
Back to front
Dynamic programming
Metaheuristic approaches
Example metaheuristic – genetic algorithms
Summary
Further reading
Slices
Search
Linear search
Binary search
Sorting
Stable sorting
Unstable sorting
Summary
Further reading
Language: English
Copyright, 1908
By THOMPSON & THOMAS
CONTENTS.
CHAPTER I.
The Bad Boy Wants to Be an Orphan—The Bad Boy Goes to an Orphan
Asylum—The Government Gives the Bad Boy’s Pa an Appointment to
Travel Over the World and Get Information About Airships, Dirigible
Balloons and Everything to Help Our Government Know What Other
Governments are Doing in Case of War 15
CHAPTER II.
No Encouragement for Inventive Genius in Orphan Home—The Boy Uses
His New Invention, a Patent Clothes Wringer, in Milking 28
CHAPTER III.
The Boy Escapes from Orphan Asylum—The Boy and His Chum Had Red
Letter Days—The Boy is Adopted by New Friends 42
CHAPTER IV.
A Bad Railroad Wreck—The Boy Contrasts Their Ride to One in a Parlor
Car—The Lawyer is the Greatest Man on Earth—The Boy Settles His
Claim for $20 55
CHAPTER V.
The Bad Boy Leaves St. Louis in a Balloon—The Boy Makes a Trip to San
Francisco and Joins Evans’ Fleet—The Police Arrest Boy and Tie Up
Balloon 67
CHAPTER VI.
The Balloon Lands in Delaware—The Boy Visits the Battleships—They 78
Scour the Boy With a Piece of Brick and Some Laundry Soap—The Boy
Investigates the Mechanism of the Battleships—The Boy Goes With the
Ships as a Mascot
CHAPTER VII.
A Storm Comes from the Coast of Cuba—Everyone Goes to Sleep on the
Ship Except the Watchman and Pilot—The Bad Boy is Put in the
Dungeon—The Captain Says to Throw the Boy Overboard to Feed the
Sharks 91
CHAPTER VIII.
The Boy Dresses Up in His Sunday Clothes and Tells the Captain He is
Ready to Die—The Crew Throw a Steer Overboard to Feed a School of
Sharks—The Boy Produces His New Electric Battery—The Bad Boy
Makes a Trip to France to Meet His Pa 104
CHAPTER IX.
The Bad Boy Arrives in France—The Boy’s Pa is Suspected of Being an
Anarchist—The Boy Finds Pa Seated at a Large Table Bragging About
America—He Told Them the Men in America Were All Millionaires and
Unmarried 131
CHAPTER X.
Pa Had the Hardest Time of His Life in Paris—Pa Drinks Some Goat Milk
Which Gives Him Ptomaine Poison in His Inside Works—Pa Attends the
Airship Club in the Country—Pa Draws on American Government for
$10,000 145
CHAPTER XI.
The Boy and His Pa Leave France and Go to Germany, Where They Buy
an Airship—They Get the Airship Safely Landed—Pa and the Boy With
the Airship Start for South Africa—Pa Shows the Men What Power He
Has Over the Animal Kingdom 157
CHAPTER XII.
All Kinds of Climates in South Africa—Pa Hires Men to Capture Wild
Animals—The Boy and His Pa Capture Some Tigers and a Big Lion—
They Have a Narrow Escape from a Rhinoceros 170
CHAPTER XIII.
Pa Was a Hero After Capturing Two Tigers and a Lion—Pa Had an Old
Negro With Sixty Wives Working for Him—Pa Makes His Escape in
Safety—Pa Goes to Catch Hippopotamusses 181
CHAPTER XIV.
Pa Was Blackmailed and Scared Out of Lots of Money—Pa Teaching the
Natives to Speak English—Pa Said the Natives Acted Like Human
Beings—Pa Buys Some Animals in the Jungle 194
CHAPTER XV.
The Idea of Airships is All Right in Theory, but They are Never Going to Be
a Reliable Success—Pa Drowns the Lions Out With Gas—The Bad Boy
and His Pa Capture a Couple of Lions—Pa Moves Camp to Hunt Gorillas 207
CHAPTER XVI.
The Boy’s Pa Shows Bravery in the Jungles in Africa—Four Gorillas Chase
Pa—The Boy and His Pa Don’t Sleep Much at Night—The Boy
Discovers a Marsh Full of Wild Buffaloes 220
CHAPTER XVII.
The Boy’s Experience With an African Buffalo—The Boy’s Pa Shoots
Roman Candles to Scare the Buffaloes—The Boy’s Pa Tames the Wild
Animals 234
CHAPTER XVIII.
The Boy and His Pa Start for the Coast in an Airship—Pa Saluted the
Crowd as We Passed Over Them—The Airship Lands Amid a Savage
Tribe—The King of the Tribe Escorts Pa and the Boy to the Palace 246
CHAPTER XIX.
The Boy’s Pa Becomes King over the Negroes—Pa Shows the Natives
How to Dig Wells—Pa Teaches the Natives to become Soldiers—The
Boy Uses a Dozen Nigger Chasers and Some Roman Candles—The
Boy, His Pa and the Natives Assist at the 4th of July Celebration 258
ILLUSTRATIONS.
The private took me by the wrist and gave me a jerk and landed me
in the laundry, and told me to strip off, and when I had removed my
clothes and folded them and laid them on a table, he took the clothes
away from me, and then told me to climb into a laundry tub, and he
turned cold water on me and gave me a bar of yellow laundry soap,
and after I had lathered myself he took a scrubbing brush, such as
floors are scrubbed with, and proceeded in one full swoop to peel the
hide off of me with a rough crash towel till you could see my veins
and arteries, and inside works as well as though you had used X-
rays, and when I was ready to die and wanted to, I yelled murder,
and he put his hand over my mouth so hard that he loosened my
front teeth, and I guess I died right there or fainted, for when I came
to, and thought the resurrection morning, that they used to tell me
about in the Sunday School, had come. I found myself dressed in a
sort of combination shirt and drawers, like a bunny nightie, made of
old saddle blankets, and he told me that was the uniform of the
orphanage and that I could go out and play for fifteen minutes, after
which the bell would ring and I could go from play to work. Gosh, but
I was glad to get out doors, but when I began to breathe the fresh air,
and scratch myself where the saddle blanket clothes pricked me,
about fifty boys, who were evidently sophomores in the orphanage,
came along, and made a rush for me, to haze me as a freshman.
Well, they didn’t do a thing to me. They tied a rope around one
ankle, and threw the rope over a limb, and pulled me off the ground,
and danced a war dance around me and run thistles up my trouser’s
legs, and spanked me with a board with slivers in it, and let me down
and walked over me in a procession, singing “There’ll be a hot time
in the old town to-night.” I laughed all the time, because that is the
way freshmen do in college when they are being murdered, and I
thought my new associates would like me better if I died game. Just
before I died game the bell rang, and the one eyed pirate and his
chief of staff came out and said we would go to work, and the boys
were divided into squads and put to work, some husking corn, others
sweeping up dead leaves, others milking cows, and doing everything
necessary around a farm.
Before I was set to work I had a few minutes of silent reflection, and I
thought of my changed condition from my porcelain lined bath tub
with warm water and soft towels, to that bath in the laundry, and the
skinning process of preparing a boy for a better life.
Then what do you suppose they set me to work at? Skinning bull
heads and taking out the insides. It seems the boys catch bull heads
in a pond, and the bull heads are used for human food, and the
freshest boys were to dress them. Well, I wasn’t going to kick on
anything they gave me for a stunt, so I put on an apron, and for four
hours I skinned and cut open bull heads in a crude sort of way, until I
was so sick I couldn’t protect myself from the assaults of the live bull
heads, and the cook said I done the job so well that she would ask to