Documentupload - 623download Full Ebook of Mastering Rust Mastering Computer Science 1St Edition Sufyan Bin Uzayr Editor Online PDF All Chapter

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 69

Mastering Rust Mastering Computer

Science 1st Edition Sufyan Bin Uzayr


Editor
Visit to download the full and correct content document:
https://ebookmeta.com/product/mastering-rust-mastering-computer-science-1st-editio
n-sufyan-bin-uzayr-editor/
More products digital (pdf, epub, mobi) instant
download maybe you interests ...

Mastering GNOME Mastering Computer Science 1st Edition


Sufyan Bin Uzayr Editor

https://ebookmeta.com/product/mastering-gnome-mastering-computer-
science-1st-edition-sufyan-bin-uzayr-editor/

Mastering Bootstrap: A Beginner's Guide (Mastering


Computer Science) 1st Edition Sufyan Bin Uzayr (Editor)

https://ebookmeta.com/product/mastering-bootstrap-a-beginners-
guide-mastering-computer-science-1st-edition-sufyan-bin-uzayr-
editor/

Mastering Android Studio: A Beginner's Guide (Mastering


Computer Science) 1st Edition Sufyan Bin Uzayr

https://ebookmeta.com/product/mastering-android-studio-a-
beginners-guide-mastering-computer-science-1st-edition-sufyan-
bin-uzayr/

Mastering Rust: A Beginner's Guide 1st Edition Sufyan


Bin Uzayr

https://ebookmeta.com/product/mastering-rust-a-beginners-
guide-1st-edition-sufyan-bin-uzayr/
Mastering Rust: A Beginner's Guide 1st Edition Sufyan
Bin Uzayr

https://ebookmeta.com/product/mastering-rust-a-beginners-
guide-1st-edition-sufyan-bin-uzayr-2/

Mastering Python for Web: A Beginner's Guide (Mastering


Computer Science) 1st Edition Sufyan Bin Uzayr

https://ebookmeta.com/product/mastering-python-for-web-a-
beginners-guide-mastering-computer-science-1st-edition-sufyan-
bin-uzayr/

Mastering R: A Beginner's Guide Sufyan Bin Uzayr


(Editor)

https://ebookmeta.com/product/mastering-r-a-beginners-guide-
sufyan-bin-uzayr-editor/

Mastering Vue.js: A Beginner's Guide 1st Edition Sufyan


Bin Uzayr

https://ebookmeta.com/product/mastering-vue-js-a-beginners-
guide-1st-edition-sufyan-bin-uzayr/

Mastering Unity: A Beginner's Guide 1st Edition Sufyan


Bin Uzayr

https://ebookmeta.com/product/mastering-unity-a-beginners-
guide-1st-edition-sufyan-bin-uzayr/
Mastering Rust

Mastering Rust helps the reader master the powerful Rust


programming language for creating stable and versatile applications
and projects.
Rust is a dependable and robust programming language that was
created with today’s needs in mind, which is something that several
other scripting languages lack.
Rust was developed to provide high functions comparable to
those of C and C++, and with a focus on code integrity, which is,
arguably, lacking in languages such as C. Rust is a dynamically typed
language that emphasizes performance and reliability, particularly in
parallelism and storage organization. Rust allows you to store data
on the tower or the shedload, and it recognizes the importance of
performance optimization. It permits even more effective memory
usage as well as faster memory management than most other
programming languages in its league.
Make no mistake about it – Rust is a programming language with
a strong learning curve, and is considered complicated by even the
most experienced of developers. The rewards for learning Rust are
aplenty, but the learning process itself requires a good deal of
determination and hard work.
Nonetheless, Rust aims to provide a secure, concurrent, and
practical systems language in ways that other programming
languages do not, and this is primarily why Rust is often the
preferred choice for building complex and highly stable apps. Rust
boasts of advantages over many other programming languages in
terms of expressiveness, speed, sound design, and memory storage.
Though the language is new and constantly changing with time,
there is an excellent opportunity in this field for future employment.
That said, to learn the reliable language that is Rust, you need to
have an equally reliable companion guide in your hands, and this is
where Mastering Rust comes in.
With Mastering Rust, learning Rust programming language
becomes a charm, and will undoubtedly help readers advance their
careers.
The Mastering Computer Science series is edited by Sufyan bin
Uzayr, a writer and educator with more than a decade of experience
in the computing field.
Mastering Computer Science
Series Editor: Sufyan bin Uzayr

Mastering Rust: A Beginner’s Guide


Divya Sachdeva, Faruq KC, and Aruqqa Khateib

Mastering Visual Studio Code: A Beginner’s Guide


Jaskiran Kaur, D Nikitenko, and Mathew Rooney

Mastering Django: A Beginner’s Guide


Jaskiran Kaur, NT Ozman, and Reza Nafim

Mastering Ubuntu: A Beginner’s Guide


Jaskiran Kaur, Rubina Salafey, and Shahryar Raz

Mastering KDE: A Beginner’s Guide


Jaskiran Kaur, Mathew Rooney, and Shahryar Raz

Mastering Kotlin: A Beginner’s Guide


Divya Sachdeva, Faruq KC, and Aruqqa Khateib

For more information about this series, please visit:


https://www.routledge.com/Mastering-Computer-Science/book-
series/MCS

The “Mastering Computer Science” series of books are


authored by the Zeba Academy team members, led by
Sufyan bin Uzayr.

Zeba Academy is an EdTech venture that develops courses


and content for learners primarily in STEM fields, and offers
education consulting to Universities and Institutions
worldwide. For more info, please visit https://zeba.academy
Mastering Rust
A Beginner’s Guide

Edited by Sufyan bin Uzayr


First edition published 2023
by CRC Press
6000 Broken Sound Parkway NW, Suite 300, Boca Raton, FL 33487-2742
and by CRC Press
4 Park Square, Milton Park, Abingdon, Oxon, OX14 4RN
CRC Press is an imprint of Taylor & Francis Group, LLC
© 2023 Sufyan bin Uzayr
Reasonable efforts have been made to publish reliable data and information, but
the author and publisher cannot assume responsibility for the validity of all
materials or the consequences of their use. The authors and publishers have
attempted to trace the copyright holders of all material reproduced in this
publication and apologize to copyright holders if permission to publish in this form
has not been obtained. If any copyright material has not been acknowledged
please write and let us know so we may rectify in any future reprint.
Except as permitted under U.S. Copyright Law, no part of this book may be
reprinted, reproduced, transmitted, or utilized in any form by any electronic,
mechanical, or other means, now known or hereafter invented, including
photocopying, microfilming, and recording, or in any information storage or
retrieval system, without written permission from the publishers.
For permission to photocopy or use material electronically from this work, access
www.copyright.com or contact the Copyright Clearance Center, Inc. (CCC), 222
Rosewood Drive, Danvers, MA 01923, 978-750-8400. For works that are not
available on CCC please contact mpkbookspermissions@tandf.co.uk
Trademark notice: Product or corporate names may be trademarks or registered
trademarks and are used only for identification and explanation without intent to
infringe.

Library of Congress Cataloging–in–Publication Data


Names: Bin Uzayr, Sufyan, editor.
Title: Mastering Rust : a beginner’s guide / edited by Sufyan bin Uzayr.
Description: First edition. | Boca Raton : CRC Press, 2022. | Includes
bibliographical references and index.
Identifiers: LCCN 2022020964 (print) | LCCN 2022020965 (ebook) | ISBN
9781032319049 (hbk) | ISBN 9781032319018 (pbk) | ISBN 9781003311966
(ebk)
Subjects: LCSH: Rust (Computer program language) | Computer programming.
Classification: LCC QA76.73.R87 M355 2022 (print) | LCC QA76.73.R87 (ebook)
| DDC 005.13/3--dc23/eng/20220805
LC record available at https://lccn.loc.gov/2022020964
LC ebook record available at https://lccn.loc.gov/2022020965

ISBN: 9781032319049 (hbk)


ISBN: 9781032319018 (pbk)
ISBN: 9781003311966 (ebk)
DOI: 10.1201/9781003311966
Typeset in Minion
by Deanta Global Publishing Services, Chennai, India
Contents

Mastering Computer Science Series Preface


About the Editor

Chapter 1 Getting Started with Rust


WHAT EXACTLY IS RUST?
Who Rust Is for
Rust’s Increasing Popularity
What Makes the Rust Programming Language
Unique?
Concurrent Programming Has Been Simplified
Some Challenges to Overcome while
Programming in Rust
What Is the Purpose of Rust?
Why Should We Use Rust?
Features of Rust
INSTALLING RUST
Rust in Windows Installation
Installing Rust on Linux or macOS
Updating and Uninstalling Rust
RUST FIRST PROGRAM
Procedure for Creating, Compiling, and
Running the Program
REASONS WHY RUST IS THE WAY OF THE
FUTURE
Rust vs. Other Languages
Advantages of Rust vs. C++
Advantages of Rust vs. Java
Advantages of Rust vs. Python
Advantages of Rust vs. Go
What Makes Rust the Future?
Rust Increased the Safety of Memory
Rust’s Community Is Expanding
Rust Is Quick and Adaptable
Rust Has a Wide Range of Applications
Rust Is Used by Several Large Companies

Chapter 2 Common Programming Concepts


VARIABLES IN RUST
Variable Naming Rules
Syntax
IMMUTABLE
MUTABLE
Variables and Constants: What Are the
Differences?
DATA TYPES IN RUST
Variable Declaration
Scalar Types
Integer
Illustration
Integer Range
Integer Overflow
Float
Automatic-type Casting
Number Separator
Boolean
Character
Compound Types
Tuple Type
Array Type
Accessing the Array Elements
Invalid Array Element Access
CONSTANT IN RUST
Constant Naming Convention in Rust
Constants vs. Variables
Variable and Constant Shadowing
STRING IN RUST
String Literal
String Object
Syntax
String Object – Common Methods
Illustration: new()
Illustration: to_string()
Illustration: replace()
Illustration: as_str()
Illustration: push()
Illustration: push_str()
Illustration: len()
Illustration: trim()
Illustration: split_whitespace()
Illustration: split() string
Illustration: chars()
Concatenation of the Strings with + Operator
Illustration: String Concatenation
Illustration: Type Casting
Illustration: Format! Macro
OPERATORS IN RUST
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
DECISION-MAKING IN RUST
If Statement
Syntax
If else statement
Syntax
Flowchart
Nested If
Syntax
Match Statement
Syntax
Using an “if” statement within a “let” statement
Syntax
LOOPS IN RUST
Loop
Syntax
Exit from Loops
While Loop
Syntax
Flowchart
While Loop Disadvantages
FOR LOOP
Syntax
Distinctions between the While Loop and For
Loop
FUNCTIONS IN RUST
Function Defining
Syntax
Function Invoking
Syntax
Illustration
Returning Value from a Function
Syntax
Function with the Parameters
Pass by Value
Pass by Reference
Passing String to a Function
COMMENTS IN RUST
TUPLE IN RUST
Destructing
ARRAY IN RUST
Array Characteristics
Array Declaration and Initialization
Syntax
Illustration: Simple Array
Illustration: Array without Data Type
Illustration: Default Values
Illustration: Array with for Loop
Illustration: Using the iter() Function
Illustration: Mutable Array
Passing Arrays as Parameters to the Functions
Illustration: Pass by Value
Illustration: Pass by Reference
The Array Declaration and Constants

Chapter 3 Understanding Ownership


WHAT EXACTLY IS OWNERSHIP?
The Stack and the Heap
Important Ownership Concepts
Rules of Ownership
Variable Scope
String Type
Memory and Allocation
Ways of Variables and Data Interact: Move
Variables and Data Interactions: Clone
Stack-Only Data: Copy
Ownership and Functions
Return Values and Scope
REFERENCES AND BORROWING IN RUST
Why Borrowing?
Mutable Reference
Restrictions of the Mutable References
Dangling References
The Referencing Guidelines
SLICES IN RUST
String Slices
Literals Are String Slices
String Slices as Parameters
Other Slices

Chapter 4 Using Structs for Related Data


WHAT IS THE DEFINITION OF A STRUCTURE?
When the Variables and Fields Have the Same
Name, Use the Field init Shorthand
Using Struct Update Syntax to Create Instances
from Other Instances
The Tuple Structs without Named Fields to
Create Different Types
Structs that Look Like Units but Don’t Have Any
Fields
Ownership of Struct Data
UPDATE SYNTAX
An Example of a Structs Program
Refactoring with the Tuples
Using Structs for Refactoring: Adding Additional
Meaning
Using Derived Traits to Add Useful Functionality
METHOD SYNTAX
Defining the Methods
Methods with More Parameters
Associated Functions
Multiple impl Blocks

Chapter 5 Enums and Pattern Matching


DEFINING AN ENUM
Enum Values
The Advantages of the Option Enum over Null
Values
THE MATCH CONTROL FLOW OPERATOR
Patterns that Bind to Values
Matching with the Option<T>
Matches Are Exhaustive
Catch-all Patterns and the _ Placeholder
CONCISE CONTROL FLOW WITH IF LET

Chapter 6 Packages, Crates, and Modules


PACKAGES AND CRATES
DEFINING MODULES TO THE CONTROL SCOPE
AND PRIVACY
PATHS FOR REFERRING TO AN ITEM IN THE
MODULE TREE
Exposing Paths with pub Keyword
Starting Relative Paths with super
Making Structs and Enums Public
BRINGING PATHS INTO THE SCOPE WITH THE
USE KEYWORD
Creating the Idiomatic use Paths
Providing New Names with the as Keyword
Re-exporting Names with pub use
SEPARATING MODULES INTO DIFFERENT FILES

Chapter 7 Error Handling


ERROR HANDLING
Unrecoverable Errors with panic!
Unwinding Stack or Aborting in Response to
a Panic
Using panic! Backtrace
RECOVERABLE ERRORS WITH THE RESULT
Shortcuts for the Panic on Error: unwrap and
expect
Propagating Errors
Shortcut for Propagating Errors: the ? Operator
The ? Operator Can Be Used in Functions that
Return Result
TO PANIC! OR NOT TO PANIC!
Examples, Prototype Code, and Tests
Cases in Which We Have More Information
than the Compiler
Guidelines for the Error Handling
Creating the Custom Types for Validation

Chapter 8 Generic Types, Traits, and Lifetimes


GENERIC DATA TYPES
In Function Definitions
In the Struct Definitions
In Method Definitions
Performance of Code Using Generics
Traits: Defining Shared Behavior
Defining a Trait
Implementing a Trait on a Type
VALIDATING REFERENCES WITH LIFETIMES
Preventing Dangling References with Lifetimes
Borrow Checker
Generic Lifetimes in the Functions

Chapter 9 I/O Project: Building a Command Line


Program
ACCEPTING THE COMMAND LINE ARGUMENTS
Saving the Argument Values in the Variables
READING A FILE
Refactoring to Improve Modularity and Error
Handling
Separation of Concerns for Binary Projects
Extracting the Argument Parser
Grouping the Configuration Values
Creating a Constructor for the Config
Fixing the Error Handling
Improving the Error Message
DEVELOPING THE LIBRARY’S FUNCTIONALITY
WITH THE TEST-DRIVEN DEVELOPMENT
WORKING WITH THE ENVIRONMENT VARIABLES
Writing Failing Test for the Case-Insensitive
search Function
Implementing search_case_insensitive Function
WRITING ERROR MESSAGES TO THE STANDARD
ERROR INSTEAD OF STANDARD OUTPUT
Checking Where Errors Are Written
Printing Errors to the Standard Error

Chapter 10 Cargo and crates.io


CUSTOMIZING BUILDS WITH THE RELEASE
PROFILES
PUBLISHING A CRATE TO CRATES.IO
Making Useful Documentation Comments
Commonly Used Sections
Documentation Comments as Tests
Commenting Contained Items
Exporting a Convenient Public API with the pub
use
Setting Up crates.io Account
CARGO WORKSPACES
Creating a Workspace
Creating the Second Package in the Workspace
INSTALLING BINARIES FROM CRATES.IO WITH
CARGO INSTALL
EXTENDING CARGO WITH THE CUSTOM
COMMANDS

Chapter 11 Concurrency and State


FEARLESS CONCURRENCY
USING THREADS TO RUN CODE
SIMULTANEOUSLY
Creating New Thread with spawn
Waiting for All the Threads to Finish Using
JoinHandle
USING MESSAGE PASSING TO THE TRANSFER
DATA BETWEEN THREADS
The Channels and Ownership Transference
Sending Multiple Values and Seeing the
Receiver Waiting
Creating Multiple Producers by Cloning the
Transmitter
SHARED-STATE CONCURRENCY
Using Mutexes to Allow Data Access from Only
One Thread at a Time
API of Mutex<T>
Sharing Mutex<T> Between Multiple Threads
EXTENSIBLE CONCURRENCY WITH SYNC AND
SEND TRAITS
Allowing Transference of the Ownership
between Threads with Send
Allowing Access from the Multiple Threads with
Sync
Implementing the Send and Sync Manually Is
Unsafe

Chapter 12 Object-oriented Programming in Rust


IMPLEMENTING AN OBJECT-ORIENTED DESIGN
PATTERN
Defining Post and Creating New Instance in the
Draft State
Storing the Text of the Post Content
Ensuring Content of a Draft Post Is Empty
Requesting a Review Changes the State of the
Post
Trade-offs of the State Pattern
MACROS
Difference between Macros and Functions
Declarative Macros with macro_rules! for
General Metaprogramming
Procedural Macros for Generating Code from
the Attributes
How to Write a Custom derive Macro
Attribute-like Macros
Function-like Macros

APPENDIX A: KEYWORDS
APPENDIX B: OPERATORS AND SYMBOLS

APPENDIX C: DERIVABLE TRAITS

APPRAISAL

BIBLIOGRAPHY

INDEX
Mastering Computer Science
Series Preface

The Mastering Computer Science covers a wide range of topics,


spanning programming languages as well as modern-day
technologies and frameworks. The series has a special focus on
beginner-level content, and is presented in an easy-to-understand
manner, comprising:

Crystal-clear text, spanning various topics sorted by relevance


A special focus on practical exercises, with numerous code samples and
programs
A guided approach to programming, with step-by-step tutorials for the
absolute beginners
Keen emphasis on real-world utility of skills, thereby cutting the redundant
and seldom-used concepts and focusing instead on industry-prevalent coding
paradigm
A wide range of references and resources to help both beginner and
intermediate-level developers gain the most out of the books

The Mastering Computer Science series of books starts from the core
concepts, and then quickly moves on to industry-standard coding
practices, to help learners gain efficient and crucial skills in as little
time as possible. The books assume no prior knowledge of coding,
so even absolute newbie coders can benefit from this series.
The Mastering Computer Science series is edited by Sufyan bin
Uzayr, a writer and educator with more than a decade of experience
in the computing field.
About the Editor

Sufyan bin Uzayr is a writer, coder, and entrepreneur with more than
a decade of experience in the industry. He has authored several
books in the past, pertaining to a diverse range of topics, ranging
from History to Computers/IT.
Sufyan is the Director of Parakozm, a multinational IT company
specializing in EdTech solutions. He also runs Zeba Academy, an
online learning and teaching vertical with a focus on STEM fields.
Sufyan specializes in a wide variety of technologies, such as
JavaScript, Dart, WordPress, Drupal, Linux, and Python. He holds
multiple degrees, including ones in Management, IT, Literature, and
Political Science.
Sufyan is a digital nomad, dividing his time between four
countries. He has lived and taught in universities and educational
institutions around the globe. Sufyan takes a keen interest in
technology, politics, literature, history, and sports, and in his spare
time, he enjoys teaching coding and English to young students.
Learn more at sufyanism.com.
Chapter 1 Getting Started
with Rust
DOI: 10.1201/9781003311966-1

IN THIS CHAPTER
Getting started
Installation
Basic program

The Rust programming language is demonstrated for both beginners


and experts. The Rust programming language is intended to improve
memory safety; however, it is still developing.

WHAT EXACTLY IS RUST?


Rust is a system programming language created in 2006 by a Mozilla
engineer named Graydon Hoare. He called it a “safe, concurrent, and
practical language” that supports the functional and imperative
paradigms.
Rust’s syntax is comparable to that of the C++ programming
language.
Rust is free and open-source software, which means that anybody
may use it for free, and the source code is openly provided so that
anyone can enhance the product’s design.
In 2016, 2017, and 2018, the Stack Overflow Developer Survey
named Rust as one of the “most liked programming languages.”
There is no such thing as direct memory management, such as
calloc or malloc. Rust manages memory internally.
Rust was developed to deliver excellent performance comparable
to C and C++ while prioritizing code safety, which is the Achilles’
heel of the other two languages. The Rust programming language is
presently employed by well-known software giants such as Firefox,
Dropbox, and Cloudflare. From startups to huge enterprises, many
firms are adopting this technology in production.

Who Rust Is for


The Rust programming language is excellent for many people for
various reasons.
Let’s have a look:

Teams of developers: Rust has shown to be quite effective for the “team
of developers.” Low-level programming code has defects that testers must
thoroughly test. However, in the case of Rust, the compiler refuses to
compile the code if it includes flaws. By working in parallel with the compiler,
the developer may concentrate on the logic of the program rather than on
the flaws.
Students: Many people can learn to construct an operating system using
Rust. The Rust team is working to make system principles more
approachable to the general public, particularly those new to programming.
Companies: Rust is used by both large and small businesses to complete
various activities. Command-line tools, web services, DevOps tooling,
embedded devices, audio and video analyses and transcoding,
cryptocurrency, bioinformatics, search engines, Internet of Things
applications, machine learning, and even large portions of the Firefox web
browser are among these activities.
Developers of open-source software: Rust is an open-source language;
the source code is available to the public. As a result, they may utilize the
source code to enhance Rust’s design.

Rust’s Increasing Popularity


Rust is the most popular programming language, according to the
Stack Overflow Developer Survey 2020, which polled approximately
65,000 developers. It also won the championship for the sixth year
in a row.
In addition, Linux kernel engineers recommended creating new
Linux kernel code in Rust in 2020. To be clear, they did not wish to
redo the entire kernel, which was built in C initially, but rather to add
new code in Rust that would function with the current infrastructure.
Linus Thorvalds, the founder of the open-source operating system
Linux, supported the idea and is eager to see the project’s
achievements.
Facebook has further extended its ties with Rust by joining the
Rust Foundation, a group created in 2021 to promote Rust
development and make it “a mainstream language of choice for
systems programming and beyond.” Rust is used by Facebook,
Amazon Web Services, Google, Huawei, Microsoft, and Mozilla.

What Makes the Rust Programming Language


Unique?
Rust is a strongly typed programming language that prioritizes speed
and safety and extraordinarily safe concurrency and memory
management. Its syntax is comparable to C++. It is an open-source
project that began at Mozilla Research. The Rust Foundation has
taken up the torch and is leading the language’s development in
2021.
Rust tackles two long-standing concerns for C/C++ developers:
memory errors and concurrent programming. This is regarded as its
primary advantage.
Of course, one might argue that contemporary C++ focuses more
on memory safety (for example, by implementing smart pointers),
but many issues remain unsolved.
One of these is a “use after free error,” which occurs when a
program continues to utilize a pointer after being freed, for example,
by running the lambda function after releasing its reference-captured
objects.
In Rust, on the other hand, the borrow checker, the compiler
component that guarantees that references do not outlive the data
they refer, is present. This feature aids in the elimination of memory
violation bugs. Such issues are recognized during the compilation
process; therefore, trash collection is not required.
Furthermore, in Rust, each reference has a lifespan, which
specifies the scope for which that reference is valid. This innovation
overcomes the problem of invalid references while also distinguishing
Rust from C and C++.
When we consider that over the last 12 years memory safety
concerns have accounted for over 70% of all security flaws in
Microsoft products, the necessity of proper memory management
becomes instantly clear. A similar figure has been reported for
Google Chrome.
There are two ways to write code in Rust: Safe Rust and Unsafe
Rust. Safe Rust imposes additional constraints on the programmer
(for example, object ownership management), guaranteeing that the
code functions properly. Unsafe Rust allows the programmer more
freedom (for example, it may work on raw C-like pointers), but the
code may fail.
The risky Rust mode gives you more possibilities, but we must
exercise extreme caution to guarantee our code is secure. To do this,
we can encase it in higher-level abstractions that ensure that all
abstraction applications are safe. As with other programming
languages, employing unsafe code should be treated with caution to
prevent undefined behavior and reduce the danger of segfaults and
vulnerabilities caused by memory insecurity.
One of the most significant advantages of Rust is its dual-mode
concept. In C++, on the other hand, we never realize we’ve written
dangerous code until our product collapses or a security breach
occurs.

Concurrent Programming Has Been Simplified


Rust simplifies concurrent programming by preventing data conflicts
at build time. When at least two independent instructions from
different threads attempt to access the same memory location
simultaneously, at least one of them attempts to write anything, and
there is no synchronization to create any precise order among the
various accesses, a data race occurs. Memory access without
synchronization is undefined.
Data races are detected in Rust. Suppose given object access
does not allow several threads (i.e., it is not designated with an
appropriate trait). In that case, it must be synchronized by a mutex,
which locks access to this specific object for other threads.
Only one thread gets access to an object to guarantee that its
operations do not damage it.
Operations on this object are atomic from the perspective of other
threads, which implies that an observed state of the object is always
valid. We cannot witness any intermediate state arising from another
thread’s action on this object. The Rust programming language can
detect and report improper actions on such objects at build time.
Other languages have synchronization techniques, but they are
unrelated to the objects to which they refer. The developer’s
responsibility is to ensure that the object is locked before using it.

Some Challenges to Overcome while Programming in


Rust
Of course, not everything is perfect. Because Rust is a new
technology, specific desirable libraries may not yet be available.
Nonetheless, the Rust package library crates.io has been rapidly
expanding since 2016, and the strong community of Rust developers
is a promising indication for future growth.
Also, for developers who aren’t used to working with a language
where problems in the code are identified at compile time, seeing a
slew of error messages might be aggravating. As a result, creating
code takes longer than in more popular languages such as Python.
Rust’s developers, on the other hand, are working hard to make
these error messages as helpful and actionable as possible.
Even if seeing so many error warnings when coding might be
annoying, keep your eye on the broader picture. Memory safety
imposed at build time avoids defects and security vulnerabilities from
occurring after our software has been released. Correcting problems
will undoubtedly cost us both our nerves and our money during this
stage.
Last but not least, creating Rust code takes extra work due to the
relatively high entrance threshold. We must devote some time to
learning the language. It is also necessary to have a solid
understanding of C++ or another object-oriented programming
language. The learning curve is far from flat.
But if we can overcome all of these challenges, the advantages of
utilizing Rust will be the ultimate reward for our work.

What Is the Purpose of Rust?


Rust is an established technology that is already in use in the
industry. It helps us control low-level details as a systems
programming language. We can store data on the stack (used for
static memory allocation) or on the heap (used for dynamic memory
allocation). RAII (Resource Acquisition Is Initialization) is an
essential programming idiom mostly associated with C++ but is also
present in Rust: once an object exits scope, its destructor is called,
and its owned resources are released. We don’t have to perform it
by hand, and we’re safe against resource leakage problems.
As a result, memory may be used more efficiently. Tilde employed
Rust in their Skylight product to rebuild several Java HTTP endpoints.
They were able to cut their memory use from 5GiB to 50MiB due to
this.
Because Rust does not have an active garbage collector, other
programming languages may utilize its projects as libraries via
foreign-function interfaces. This is a good case for existing projects
where high performance while preserving memory safety is crucial.
In such cases, Rust code may replace select areas of software where
speed is critical without rebuilding the entire product.
Rust is a low-level programming language that provides direct
access to hardware and memory, making it an excellent choice for
embedded and bare-metal development. Rust may be used to create
operating systems and microcontroller applications. In reality, several
operating systems written in Rust exist, including Redox,
intermezzOS, QuiltOS, Rux, and Tock. As I said earlier, there are
plans to create additional Linux kernel enhancements in Rust. Mozilla
uses it in their browser engines, where the language was created.
Rust’s high performance and safety are the attributes that drew
scientists to it and led to it being used for big data analysis. Rust is
lightning fast, making it an excellent choice for computational
biology and machine learning, where enormous volumes of data
must process quickly.
At CodiLime, we’re also testing whether Rust can replace C in
network contexts requiring high data speed. In our proof-of-concept,
we created an application in Rust that used DPDK libraries (written
in C) to assure speed while simultaneously ensuring memory safety.

Why Should We Use Rust?


To summarize, the significant advantages of including Rust in our
next software project are as follows:

Memory safety is ensured while maintaining high performance.


Concurrent programming is supported.
The crates.io repository has an increasing number of Rust packages.
A vibrant community is driving the language’s evolution.
Backward compatibility and stability are both guaranteed.

Features of Rust
Rust is a programming language for systems. Rust has the following
capabilities:

Zero cost abstraction


Error messages
Rust features
Minimal time
Threads without data races
Pattern matching
Move semantics
Guaranteed memory safety
Safe memory space allocation
Efficient C bindings (Figure 1.1)
1. Zero cost abstraction: We can introduce abstractions without
compromising the code’s runtime performance. It increases code quality
and readability without sacrificing runtime efficiency.
2. Error messages: Compared to GCC, C++ programming has
significantly improved error messages. In terms of clarity, Rust goes
one step farther. In our application, error messages are presented with
formatting and colors and also propose misspellings.
3. Type inference: Rust has a Type inference feature that automatically
detects the type of an expression.
4. Move semantics: A copy action may be replaced with a move
operation when a source object is a temporary object.
5. Threads without the data races: When two or more threads
simultaneously access the same memory address, this is referred to as
a data race. Because of the ownership mechanism, Rust supports
threads without data races. Only the owners of separate objects are
sent to various threads via the ownership mechanism, and two threads
can never possess the same variable with write access.
6. Pattern matching: Rust has a pattern matching capability. Pattern
matching in Rust uses patterns in conjunction with “match” expressions
to provide additional control over the program’s control flow. The
following are some pattern combinations:
– Literals
– Arrays, enums, structs, or tuples
– Variables
– Wildcards
– Placeholders

7. Guaranteed memory safety: Rust ensured memory safety by


employing the idea of ownership. Ownership compromises C’s memory
control and Java’s garbage collection. Memory space in Rust programs
is owned by variables and temporarily borrowed by other variables. This
enables Rust to ensure memory safety at compile time, rather than
relying on the garbage collector.
8. Efficient C bindings: The characteristic of “Efficient C bindings” in
Rust implies that the Rust language may interact with the C language
as it communicates itself. Rust provides a “foreign function interface” to
connect with C APIs while also leveraging its ownership structure to
ensure memory safety.
9. Safe memory space allocation: Rust uses manual memory
management, implying that the programmer has complete control over
where and when memory is created and deallocated. In C, we use the
malloc function to allocate memory and subsequently initialize it,
whereas Rust rejects these two actions with a single ‘~’ operator. This
operation converts the smart pointer into an int. A smart pointer is a
type of value that regulates when an item is released. Smart pointers
are called “smart” because they not only monitor the location of an
object but also know how to clear it up.

FIGURE 1.1 Features of Rust.

INSTALLING RUST
The first step is to install Rust. To begin, download Rust using
rustup, a command-line application for managing all Rust versions
and associated tools.

Rust in Windows Installation


On Windows, navigate to https://www.rust-lang.org/install.html and follow
the installation instructions. After completing all of the instructions, Rust will
install, and the screen will appear.

Rust’s PATH variable is automatically added to your system PATH after


installation.
The command prompt is opened, and the following command is executed:
$ rustc --version

After running this command, we should see the version number, commit
hash, and commit date.
If we do, it signifies Rust was successfully installed. Congratulations.

Installing Rust on Linux or macOS


If we are using Linux or macOS, open a terminal and enter the following
command:
$ curl https://sh.rustup.rs -sSf | sh

The program above downloads a script and begins the installation of the
rustup utility. This will install the recent version of Rust. If the installation is
successful, the following message will be displayed:
Rust is now installed.

After your next login, this installation will automatically add Rust to your
system path. If you wish to execute Rust without restarting the terminal, run
the following command in your shell to add the path to our system PATH
manually:
$ source $HOME/.cargo/env
A linker is required after installation. When you attempt to start our
Rust program, we will receive an error stating that a linker could not
be executed. It indicates that the linker is not present in our system.
C compilers always produce the right compiler. Set up a C compiler.
Furthermore, some Rust packages rely on C code and require a C
compiler.

Updating and Uninstalling Rust


Update: After installing Rust with “rustup,” update to the newest
version. To upgrade to the most recent version, use the following
command:

$ rustup update

Remove: To uninstall Rust, use the following command from the


shell:

$ rustup self uninstall

RUST FIRST PROGRAM


Let’s write a basic program in the Rust programming language. Open
the notepad file and type the following code:

fn main()
println!(“Hello, World”);

main(): It is always the first line of code in any Rust executable. Curly
brackets {} surround the main() function. The main() method doesn’t take
any arguments and does not return any value.
println!: It’s a macro in Rust. It does not contain “!” if it calls the method.
“Hello, World”: It is a string passed as an argument to println! and is
printed to the console.

Procedure for Creating, Compiling, and Running the


Program
1. Open the notepad file and write the code in it.
2. Save the file with the extension.rs.
3. Launch the command prompt.
4. Enter the directory’s path. Assume the project is
on the D drive.
5. Run the rustc command to compile the preceding
program.
6. Finally, execute the application using the
command filename.exe.

REASONS WHY RUST IS THE WAY OF THE FUTURE


Rust was named the most popular programming language in the
Stack Overflow 2020 survey, with 86% of engineers saying they will
continue to use it. For language designers, this is nothing new: Rust
has won the study every year since 2016. On Tiobe Index, Rust is
also gaining popularity, ranking #18 among the most popular
languages in September. It also scored well in our sentiment-based
ranking of functional programming languages, taking first place in
the most favorable sentiment class.
Rust, which was created in 2006 as an alternative to C++ by
former Mozilla engineer Graydon Hoare, is steadily creating a name
in the developer community. It is presently used to construct online
applications, embedded computers, distributed services, and
command-line interfaces. A good example of this popularity is
Microsoft’s gradual shift away from C++ (due to a growing number
of security problems) and toward Rust.
Why is Rust so popular among programmers when there are so
many different languages to choose from? One of the key reasons is
that Rust addressed several obvious difficulties in other languages to
the point where some developers claim that the architects of Rust
must have known all of the possible problems visible in C++ in mind.
Rust vs. Other Languages
Rust offers benefits over several other languages that are currently
popular among developers. Let us go through a few of them.

Advantages of Rust vs. C++


When compared to C++, Rust is safer. Rust protects both its
abstractions and the abstractions created by developers, whereas
C++ does not. Specific errors in C++ might result in arbitrary
behavior, but Rust assists you in focusing on what is truly essential.
And, while C/C++ remains one of the most popular programming
languages, it frequently causes issues. Rust is just easier to learn;
the learning curve is not as steep, there is no technical debt in Rust
as there is in C++, it supports more concurrency, and its speed is
comparable. Rust allows us to write unsafe code, but it always
defaults to safe code.

Advantages of Rust vs. Java


When it comes to Java, it turns out that it is significantly slower than
Rust, especially when compared to C in several sectors. On top of
that, we should consider speedier startup times and a reduced
memory footprint. Java employs Garbage Collection for memory
management, which reduces speed (but it is worth noting that it
simplifies code).

Advantages of Rust vs. Python


Rust is well-thought-out. Rust allows us to wrap statements in
lambda, and everything is an expression, making it easy to compose
specific portions of the language. Python does not do this. Rust lacks
classes; therefore, object orientation is not as developed as in
Python. Python also encounters the need to write additional tests
and production outages or runtime problems. Rust reduces the cost
of identifying and fixing potential issues.

Advantages of Rust vs. Go


Go’s expressiveness is lacking. Rust is a versatile and expressive
architecture that enables the creation of new container types
capable of holding various components, generics, traits, and
algebraic data types. We have less control over both resources and
memory while using Go.

What Makes Rust the Future?


Rust Increased the Safety of Memory
Memory management difficulties are one of the most serious
problems that developers face. In other languages, it is quite simple
to overlook a coding issue, resulting in the dreaded error code and
the effort required to discover and solve it. A far more significant
problem arises when a code error leads to security breaches in
today’s environment, this is too risky. Data security breaches in
major and popular websites or applications occur far more frequently
than we want. What’s the reason? Application flaws or
misconfigurations are often to blame.
Rust is thought to be memory-safe. Rust programming is not
permitted by dragging pointers, buffer overflows, and other memory-
related mistakes. It allows you to describe how memory should
handle and how values should be put out in it while also taking care
of the control and safety lines without sacrificing performance,
making it a valuable asset to Rust.
Improving memory safety was one of the key aims of Rust’s
creators and one of the language’s main selling factors. Their code
compiler is quite stringent, and each variable or memory location
that is utilized is examined automatically.
Suppose any syntax problems, null values, dangling modifiers, or
memory safety concerns are detected. In that case, Rust will not
compile the code and warn about unsafe code, allowing for speedy
identification and correction of the underlying issue. How does it
accomplish this?
Every value in Rust has an “ownership.” When a value is passed
or returned, ownership is transferred to a new scope one at a time.
If the “owner” of the value moves out of the scope, the value is
discarded. Rust maintains track of memory and automatically frees it
in this manner, preventing all flaws from entering the main code.
That implies there will be no surprises during runtime.
This system will examine memory management at build time,
making it easier to find and repair issues and eliminating the need
for trash collection.
However, there is more to memory than that. Building
sophisticated systems is frequently associated with significantly
computation-bound activity and generating a lot of temporary
memory. Such an offload can significantly impact the performance of
any Java Virtual Machine, and many programming languages,
including Scala, are incapable of dealing with it.
However, Rust can. It allows for the creation of memory-efficient
code without the need for memory management or the use of
modern conveniences such as closures, and it runs with little to no
runtime overhead, making it suitable for real-time or embedded
projects and easily integrating with other languages or projects.

Rust’s Community Is Expanding


Of course, the Rust community and quantity of libraries are nowhere
near as large as, say, C++. However, as the Rust programming
language grows in popularity, so does the number of developers and
enthusiasts who join. The number of community-created
frameworks, libraries, and development tools (known as “crates”) is
now close to 57,000, and more are being uploaded daily.
Rust has an active and inviting community in addition to a
growing collection of tools and frameworks. There are various places
to go if we need assistance with a problem or to learn more about
using Rust. In addition to the community chat and user forum, Rust
features an active subreddit section.

Rust Is Quick and Adaptable


Rust is regarded as a moderately fast language. It can run far
quicker than Scala when employing generic code, especially in
performance-critical jobs. There is a good chance that it will be three
times quicker than Scala or Java in some places. It is simple to pick
up and utilize other packages, and Rust’s cargo build tool simplifies
code.

Rust is Extremely Fast Due to a Few Factors

Because it is statically typed and compiled, the compiler may optimize the
code for speed.
It provides static trait dispatch, similar to C++ templates but cleaner.
It explicitly monitors variable ownership. Rust does not presume that every
variable with an address can change at any moment, allowing for
optimizations without negatively impacting the code.
It assumes that variables are immutable by default (so optimization is
easier).
It provides algebraic data types, which are also useful for optimization.
It does not have any overheads, no runtime, and no unexpected delays
owing to a lack of trash collection.
It provides no-cost abstraction.

Rust may alternatively be thought of as a programming language


comparable to C++, but it is easier to optimize and has fewer
unpleasant advanced programming capabilities.

Rust Has a Wide Range of Applications


If a project requires a secure and reliable execution environment,
away from the necessity of performance and low-level optimizations
(but high-level Rust functional programming approaches), Rust
should pass the test.
Rust is recognized as a low-level language that is best suited for
best systems, embedded programming, and other performance-
critical applications. It also used in 3D video games.

Rust Is Used by Several Large Companies


Despite being a relatively new language, developers have already
recognized Rust as a step in the right direction to boost
programming security and convenience of use. However, not only
coders are interested in Rust; corporations, particularly large ones,
have already migrated or intend to switch to Rust. Ryan Levick
(Microsoft cloud developer evangelist) stated at the AllThingsOpen
virtual conference in May 2020 that Rust as a language is “the
industry’s greatest hope for addressing multiple issues head-on.”
While Microsoft does not intend to abandon C++ anytime soon,
many of its infrastructures gradually transition to Rust.
And Microsoft isn’t the only firm that has seen the potential
benefits of moving to the Rust programming language; Dropbox,
Sentry, Amazon, and Mozilla are among the organizations that
employ the Rust programming language.
In this chapter, we covered the concept of Rust, as well as its
history, characteristics, purpose, and applications. Furthermore, we
learned about Rust installation, the first Rust program, and the
reasons why Rust is the way of the future.
Chapter 2 Common
Programming Concepts
DOI: 10.1201/9781003311966-2

IN THIS CHAPTER
Variables and mutability
Data types
Functions
Tuples
Array
Comments
Control flow

The previous chapter covered Rust’s definition, and its history,


benefits, and uses. We also learned about Rust’s installation and
basic programs.
This chapter discusses concepts in practically every programming
language and how Rust operates. At their heart, many programming
languages have a lot in common. None of the concepts described in
this chapter are unique to Rust, but we’ll explore them in the context
of Rust and explain how to use them.
Variables, fundamental types, functions, comments, and control
flow will be covered in detail. These fundamentals will be covered in
any Rust program, and knowing them early will provide us with a
solid platform to build on.

VARIABLES IN RUST
A variable is a sort of named storage that programs may access.
Simply put, a variable is a type of data structure that allows
programs to store values. In Rust, variables are linked with a specific
data type. The data type dictates the variable’s memory size and
layout, the range of values stored inside that memory, and the set of
operations on the variable.

Variable Naming Rules


This section will go through the various rules for naming variables:

A variable’s name can be letters, numbers, and the underscore character.


It starts with a letter or an underscore.
Because Rust is case-sensitive, upper- and lowercase letters are separate.

Syntax
When declaring a variable in Rust, the data type is optional. The
value assigned to the variable determines the data type.
The syntax for defining variables is as follows:

let variable_name = value; // no type-specified


let variable_name:dataType = value; //type-specified

Example:

fn main() {
let fees = 35_000;
let salary:f64 = 45_000.00;
println!(“fees {} and salary is {}”,fees,salary);
}

IMMUTABLE
By default, variables are immutable in Rust. In other words, the
value of the variable cannot change once a value is bound to a
variable name.
Let us understand this with an example:

fn main() {
let fees = 25_000;
println!(“fees is {} “,fees);
fees = 35_000;
println!(“fees changed is {}”,fees);
}

The source of the mistake is indicated in this error message; we


cannot set values to the immutable variable fees twice. This is just
one of the numerous ways Rust allows programmers to write code
while benefiting from the safety and ease of concurrency.

MUTABLE
By default, variables are immutable. To make a variable changeable,
prefix it with the term mutable. A mutable variable’s value can alter.
The syntax for defining a mutable variable is seen below:

let mut variable_name = value;


let mut variable_name:dataType = value;

Example:

fn main() {
let mut fees:i32 = 35_000;
println!(“fees is {} “,fees);
fees = 45_000;
println!(“fees changed {}”,fees);
}

Variables and Constants: What Are the Differences?


The inability to modify the value of a variable reminds us of another
programming notion seen in most other languages: constants. Like
immutable variables, constants are values attached to a name and
cannot be changed, but there are a few distinctions between
constants and variables.
To begin with, we are not permitted to use mut with constants.
Constants are not just immutable by default; they are also
Another random document with
no related content on Scribd:
“Then, as soon as the last of the performers had cleared the cave,
I followed my guide, and with a throbbing head, and full of a sense of
strange sickness, I went to the house where I was staying.
“I lay down upon my bed, but could not sleep; and as early as I
dared I went round to my little Martarae’s home—Martarae was her
native name. Her mother met me, said that the child would not come
out in the sun to-day, that I might see her for a moment if I pleased,
but that she was not very well.
“Sweet little soul! I found her lying on her little bed, with a proud
light in her eyes, and a very flushed face.
“A fortnight later the light flesh wounds were healed. She showed
me her breast, confided to me the story, and asked me if I did not
think she had much to be proud of.
“‘Will you keep a secret?’ I asked her. She gave me her promise,
and I told her how I had seen the whole thing, and all my fears for
her.
“A week later she was orphaned. Her mother was stung by a
deadly scorpion, and died in an hour, and I made the child my care.
“She has travelled everywhere with me ever since, and you see
how fair and sweet she is, and how beautifully she speaks our
English. She is barely twelve, is naturally gifted, and is the very light
of my life.”
“Would she let me see her breast, Ralph, do you think?”
Hammond asked.
Bastin smiled, and spoke a word to the child, and she, rising to her
feet and smiling back at him, unfastened the broach at her throat,
and, laying back her breast-covering, showed the gleaming, shiny
scars. Then as she re-covered her chest, she said softly:
“Ralph has taught me that those gods were evil; but though I shall
ever wear this cross in the flesh of my breast, I shall ever love the
Christ who died on the world’s great cross at Calvary.”
“It is a most marvellous story, Ralph,” he said tearing his eyes
away from the child’s clear, searching gaze.
“The more marvellous because absolutely true,” returned Bastin.
Then, addressing Viola, and relapsing, of course, into English for
her sake, he explained who Tom Hammond was, and that he (Ralph)
was going to be associated with him on the same great newspaper.
“Mr. Hammond and you, Viola, must be real good friends,” he
added.
“Sure, daddy!” the girl said smilingly; “I like him much already——”
She lifted herself slightly until she rested on her knees, and
stretching one hand across the hearthrug to Tom Hammond, she laid
the other in her guardian’s, as she went on:
“Mr. Hammond is good! I know, I know, for his eyes shine true.”
A ripple of merry laughter escaped her, as she gazed back into her
guardian’s face, and added:
“But you, daddy, are always first.”
CHAPTER XI.
“LONG ODDS.”

For a wonder, Tom Hammond could not sleep. Usually, when the
last thing had been done, and he was assured that everything was in
perfect train for the morning’s issue, he ate a small basin of boiled
milk and bread, which he invariably took by way of a “night-cap,”
then went to bed, and slept like a tired ploughman. But to-night
slumber would have none of him.
“It must be the various excitements of the day,” he muttered. “That
story of Ralph’s Caribbean child was enough to keep a fellow’s brain
working for a week. Then there was meeting Ralph so unexpectedly,
just, too, when I so lusted for his presence and help. Then there was
that Joyce item——”
His mind trailed off to the scene of the morning, every item of it
starting up in a new and vivid light. Suddenly he recalled the booklet
Mrs. Joyce had given him.
“I can’t sleep,” he murmured; “I’ll find that thing and read it.”
His fingers sought the electric switch. The next moment the room
was full of light. He got out of bed, passed quickly through to his
dressing-room, found the coat that he had worn that morning, and
secured the booklet.
He went back again to bed, and, lying on his elbow, opened the
dainty little printed thing and began to read thus:
“LONG ODDS”
“You don’t say so! Where on earth has she gone?”
“I can’t say, sir, but it’s plain enough she is missing. Hasn’t been
seen since last night when she went up to her room.”
I was put out, I own; my man on waking me had informed me that
the cook was missing; she had gone to bed without anything being
noticed amiss, and was now nowhere to be found. She was always
an odd woman, but a capital cook. What had become of her? The
very last sort of person to disappear in this way—a respectable
elderly Scotchwoman—really quite a treasure in the country; and the
more I thought of it while I dressed, the more puzzled I became. I
hardly liked to send for the police; and then again it was awkward,
very—people coming to dinner that day. It was really too bad.
But I had scarcely finished dressing when in rushed my man
again. I do so dislike people being excited, and he was more than
excited.
“Please, sir, Mr. Vend has come round to see you; his coachman
has gone—went off in the night, and hasn’t left a trace behind, and
they say the gardener’s boy is with him.”
“Well,” said I, “it is extraordinary; tell Mr. Vend I’m coming; stay, I’ll
go at once.”
It was really past belief—the three of them! After an hour’s talk
with Vend, no explanation offered itself, so we decided to go to town
as usual.
We walked down to the station, and saw at once something was
wrong. Old Weeks, the stationmaster, was quite upset: his
pointsman was missing, and the one porter had to take up his duty.
However, the train coming up, we had no time to question him, but
jumped in. There were three other people in the compartment, and
really I thought I was going off my head when I heard what they were
discussing. Vend, too, didn’t seem to know if he was on his head or
his heels. It was this that startled us so: “What can have become of
them all?”
I heard no more. I really believe I swooned, but at the next station
—a large one—we saw consternation on every face. I pinched
myself to see if I was dreaming. I tried to persuade myself I was.
Vend looked ghastly. A passenger got in; he did not look quite so
dazed as some did, but savage and cross. For a time none spoke; at
last someone said aloud—I don’t think he expected an answer—
“What on earth’s become of them?” and the cross looking man,
who got in last, growled out,
“That’s the worst of it; they are not on earth, they are gone. My boy
always said it would be so; from the very first moment I heard it, I
knew what had happened; often he has warned me. I still have his
voice ringing in my ears.
“‘I tell you, in that night there shall be two men in one bed: the one
shall be taken, and the other shall be left.’ (Luke xvii. 34.)
“I know only too well ‘that night’ was last night. I’ve often prayed
for it without thinking, and so I daresay have you: ‘Thy kingdom
come.’ It makes me so savage I don’t know what to do.”
Now, I was an atheist, and did not believe the Bible. For the last
thirty years (I am past fifty) I had stuck to my opinions, and when I
heard men talk religious trash I invariably objected.
But this seemed altogether different. I tell you, for a thousand
pounds I couldn’t have said a word. I just hoped it would all turn out
a dream, but the further we went, the more certain it became that we
were all awake, and that by some unaccountable visitation of
Providence a number of people had suddenly disappeared in the
night.
The whole of society was unhinged; everybody had to do
somebody’s else’s work. For instance, at the terminus, a porter had
been put into Smith’s stall, as the usual man was missing. Cabs
were not scarce, but some of those who drove them seemed
unlicensed and new to their work. The shutters in some of the shops
were up, and on getting to my bank I heard the keys had only just
been found.
Everyone was silent, and afraid lest some great misfortune was
coming. I noticed we all seemed to mistrust one another, and yet as
each fresh clerk, turned up late, entered the counting-room, a low
whisper went round. The chief cashier, as I expected, did not come.
The newspapers no one cared to look at; there seemed a tacit
opinion that they could tell us nothing.
Business was at a standstill. I saw that very soon. I hoped as the
day wore on that it would revive, but it did not. The clerks went off
without asking my permission, and I was left alone. I felt I hated
them. I did not know what to do. I could not well leave, else they
might say the bank had stopped payment, and yet I felt I could not
stay there. Business seemed to have lost its interest, and money its
value. I put up the shutters myself, and at once noticed what a
change had come over the City while I had been at the bank. Then
all were trying to fill the void places; now it seemed as if the attempt
had failed.
In the City some of the streets had that dismal Sunday
appearance, while a few houses had been broken into; but in the
main thoroughfares there was a dense mass of people, hurrying, it
struck me, they knew not where. Some seemed dazed, others
almost mad with terror. At the stations confusion reigned, and I heard
there had been some terrible accidents. I went into my club, but the
waiters had gone off without leave, and one had to help oneself.
As evening came on, I saw the lurid reflection of several fires, but,
horrible to say, no one seemed to mind, and I felt myself that if the
whole of London were burnt, and I with it, I should not care. For the
first time in my life I no longer feared Death: I rather looked on him
as a friend.
As the gas was not lit, and darkness came down upon us, one
heard cries and groans. I tried to light the gas, but it was not turned
on. I remembered there was a taper in the writing-room. I went and
lit it, but of course it did not last long. I groped my way into the
dining-room, and helped myself to some wine, but I could not find
much, and what I took seemed to have no effect; and when I heard
voices, they fell on me as if I were in a dream. They were talking of
the Bible, though, and it now seemed the one book worth thinking of,
yet in our vast club library I doubt if I should have found a single
copy.
One said: “What haunts me are the words ‘Watch therefore.’ You
can’t watch now.”
I thought of my dinner party. Little had I imagined a week ago,
when I issued the invitations, how I should be passing the hour.
Suddenly I remembered the secretary had been a religious fanatic,
and I made my way slowly to his room, knocking over a table, in my
passage, with glasses on it. It fell with a crash which sounded
through the house, but no one noticed it. By the aid of a match I saw
candles on his writing table and lit them. Yes! as I thought, there was
his Bible. It was open as if he had been reading it when called away,
and another book I had never seen before lay alongside of it—a sort
of index.
The Bible was open at Proverbs, and these verses, being marked,
caught my eye:
“Because I have called and ye refused, I have stretched out My
hand and no man regarded; I also will laugh at your calamity; I will
mock when your fear cometh.”
I had never thought before of God laughing—of God mocking. I
had fancied man alone did that. Man’s laughing had ended now—I
saw that pretty plain.
I had a hazy recollection of a verse that spoke of men wanting the
rocks to fall on them; so looked it up in the index. Yes, there was the
word “Rock,” and some of the passages were marked with a pencil.
One was Deut. xxxii. 15: “He forsook God which made him, and
lightly esteemed the Rock of our Salvation.”
Perhaps he marked that passage after he had had a talk with me.
How well I remember the earnestness with which he pressed
salvation upon me that day—explaining the simplicity of trusting
Christ and His blood for pardon—and assuring me that if I only
yielded myself to the Lord I should understand the peace and joy he
talked about. But it was no use. I remember I only chaffed him, and
said mockingly that his God was a myth, and time would prove it,
and he answered,
“Never. ‘Heaven and earth shall pass away, but My Word shall not
pass away.’ He may come to-night.”
I laughed and said, “What odds will you take? I lay you long ones.”
Another passage marked was 1 Samuel ii. 2, “Neither is there any
rock like our God,” and lower still “Man who built his house upon a
rock.”
I had no need to look that out. I knew what it referred to, and then
my eye caught Matt. xxvii. 51, “The earth did quake, and the rocks
rent.” That was when Christ died to save sinners, died to save me—
and yet I had striven against Him all my life. I could not bear to read
more. I shut the book and got up. There were some texts hanging
over the fireplace:
“Repent ye therefore, and be converted, that your sins may be
blotted out.”—Acts iii. 19.
“The blood of Jesus Christ His son cleanseth us from all sin.”—1
John i. 7.
“Now is the accepted time; behold, now is the day of salvation.”—2
Cor. vi. 2.
As I turned to leave the room these caught my eye, and I said,
“Well, I have been a fool.”
Tom Hammond looked up from the little booklet,—a look of
bewilderment was in his eyes, a sense of blankness, almost of
stupefaction, in his mind. Like one who, half stunned, passes
through some strange and wondrous experience, and slowly recalls
every item of that experience as fuller consciousness returns, he
went, mentally, slowly over the story of the little book.
“The verisimilitude of the whole story is little less than startling,” he
murmured. His eyes dropped upon the book again, and he read the
last line aloud: “Well, I have been a fool.”
Slowly, meditatively, he added: “And I, with every other otherwise
sane man who has been careless as to whether such things are to
be, am as big a fool as the man in that book!”
He laid the dainty little messenger down on the table by his
bedside. His handling of the book was almost reverential. Reaching
to the electric lever, he switched off the light. He wanted to think, and
he could think best in the dark.
“Of course, I know historically,” he mused, “all the events of the
Christ’s life, His death, His resurrection, and—and——Well, there, I
think, my knowledge ends. In a vague way I have always known that
the Bible said something of a great final denouement to all the World
Drama—an award time of some kind, a millennium of perfect—
perfect—well perfect everything that is peaceful and——Oh, I don’t
know much about it, after all. I am very much in a fog, I see, for Mrs.
Joyce and that booklet both speak of a return of Christ into the air,
whither certain dead and certain living are to be caught up to be with
Him and to begin an eternity of bliss.”
For a moment or two he tried to disentangle his many thoughts;
then, with a weary little sigh, he gave up the task, murmuring: “I
certainly am not ready for any such event. If there is to be a hideous
leaving behind of the unready, then I should be left to all that
unknown hideousness.”
A myriad thoughts crowded upon his brain. He gave up, at length,
the perplexing attempt to think out the problem, telling himself that
with the coming of the new day he would begin a definite search for
the real facts of this great mystery—the second coming of Christ.
By an exercise of his will he finally settled himself to sleep.
CHAPTER XII.
THE CENTRE OF THE EARTH.

“Will you come into my workroom, Mr. Hammond? It is a kind of


sanctum to me as well as a workroom, and I always feel that I can
talk freer there than anywhere else.”
It was the Jew, Abraham Cohen, who said these words. His visitor
was Tom Hammond. It was the morning after that Tom Hammond
had been troubled about “Long Odds” and its mysterious subject.
Jew and Gentile had had a few moments’ general talk in the
sitting-room downstairs, but Cohen wanted to see his visitor alone—
to be where nothing should interrupt their conversation.
Tom Hammond’s first vision of Cohen’s workroom amazed him. As
we have seen before, the apartment was a large one, and, besides
being a workroom, partook of the character of a study, den, sanctum
—anything of that order that best pleases the reader.
But it was the finished work which chiefly arrested the attention of
Tom Hammond, and in wondering tones he cried: “It is all so
exquisitely wrought and fashioned! But what can it be for?”
Cohen searched his visitor’s face with his deep grave eyes.
“Will you give me your word, Mr. Hammond,” he asked, “that you
will hold in strictest confidence the fact that this work is here in this
place, if I tell you what it is for?”
“I do give you my word of honour, Mr. Cohen.” As he spoke, Tom
Hammond held forth his hand. The Jew grasped the hand, there was
an exchange of grips; then, as their clasp parted, the Jew said:
“I do not wish to bind you to any secrecy as to the fact that such
work as this is being performed in England, but only that you should
preserve the secret of the whereabouts of the work and workers.”
With a sudden glow of pride—it flashed in his eyes, it rang in his
tones—he cried, “This work is for the New Temple!”
“The New Temple? I don’t think I quite understand you, Mr. Cohen.
Where is this temple being built?” There was amaze in Tom
Hammond’s voice.
“It is not yet begun,” replied the Jew. “That is, the actual rearing
has not yet begun, though the preparations are well forward. The
New Temple is to be at Jerusalem, Mr. Hammond.”
The ring of pride deepened in his voice as he went on: “There can
be no other site for the Temple of Jehovah save Zion, the city of our
God, beautiful for situation, the joy of the whole earth—the centre of
the world, Mr. Hammond.”
As he talked, Tom Hammond, watching him intently, saw how the
soul of the man and the hope of the true Israelite shone out of his
eyes.
Crossing the room to where a chart of the world (on Mercator’s
Projection) hung on the wall, the Jew took an inch-marked straight-
edge, and laying one end of it on Barrow Point, Alaska, he marked
the spot on the straight-edge where it touched Jerusalem. From
Jerusalem to Wrangel Land, Siberia, farthest east, he showed by his
straight-edge that practically he got the same measurement as when
from the west. From Jerusalem to North Cape, Scandinavia, and
from Jerusalem to the Cape of Good Hope, he showed again was
each practically the same distance.
“Always, always, is Zion the centre of the inhabited earth!” he cried
in quiet, excited tones. Moving quickly back to Hammond’s side, he
said: “Did you ever think of this, sir, that, practically speaking, all the
nations west of Jerusalem (those of Europe) write from west to east
—that is, towards the city of our God; whilst all the Asiatic races
(those east of Zion) write from east to west—just the opposite,—but
always towards Zion? No, no, sir; there can be no other place on
earth for the New Temple of Jehovah save Jerusalem. Read Ezekiel,
from the fortieth chapter, sir, and you will see how glorious a Temple
Jehovah is to have soon. ‘Show the house to the people of Israel,’
God said in vision to His prophet, ‘and let them build it after the sum,
the pattern which I show you.’ And that, sir, is what we are doing.”
“Who are the we who are doing this?” Tom Hammond’s face was
as full of wonder as his voice. “Who,” he continued, “makes the
plans, gives the orders, finds the funds?”
“Wealthy, patriotic men of our people, sir. We as a race are
learning that soon the Messiah will come, and we are proving our
belief by preparing for the House of our God. Italian Jews all over
Italy are carving the richest marbles; wrought iron, wondrous works
in metal, gold and silver ornaments, cornices, chapiters, bells for the
high priest’s robes, and a myriad other things are being prepared; so
that the moment the last restriction on our land—the land of our
fathers, the land which Jehovah gave unto our forefather Abraham,
saying, ‘Your seed shall possess it’—is removed, we shall begin to
ship the several prepared parts of the Temple to Palestine, as the
Gentiles term our land.”
A curious little smile flittered over his face as he added,
“The very march of modern times in the East, Mr. Hammond, is all
helping to make the consummation of our work more easy. The new
railways laid from the coast to Jerusalem are surely part of the
providence of our God. When Messiah comes, sir, we shall be
waiting ready for Him, I trust.”
“But do you not know,” Tom Hammond interrupted, “that according
to every record of history as well as the New Testament, all
Christendom has believed, for all the ages since, that the Messiah
came nearly two thousand years ago?”
“The Nazarene?”
There was as much or more of pity than scorn in the voice of the
Jew as he uttered the word.
“How could He be the Messiah, sir?” he went on. “Could any good
thing come out of Nazareth? Besides, our Messiah is to redeem
Israel, to deliver them from the hand of the oppressor, and to gather
again into one nation all our scattered race. No, no! a thousand
times No! The Nazarene could not be our Messiah!”
Turning quickly to Hammond, he asked, “Are you a Christian, sir?”
For a moment Tom Hammond was startled by the suddenness, the
definiteness, of the question. He found no immediate word of reply.
“You are a Gentile, of course, Mr. Hammond,” the Jew went on;
“but are you a Christian? For it is a curious fact that I find very few
Gentiles whom I have met, even professed Christians, and fewer still
who ever pretend to live up to their profession.”
Tom Hammond recovered himself sufficiently to say:
“Yes, I am a Gentile, of course, and I suppose I am—er——”
It struck him, as he floundered in the second half of his reply, as
being very extraordinary that he should find it difficult to state why he
supposed he was a Christian. While he hesitated the Jew went on:
“Why should you say you suppose, sir? Is there nothing distinctive
enough about the possession of Christianity to give assurance of it to
its possessor? I do not suppose I am a Jew, sir (by religion I mean,
and not merely by race.) No, sir, I do not suppose, for I know it.
There is all the difference in the world, it seems to me, sir, between
the mere theology and the religion of the faith we profess. The
religion is life, it seems to me, sir; theology is only the science of that
life.”
Both men were so utterly absorbed in their talk that they did not
hear a touch on the handle of the door. It was only as it opened that
they turned round. Zillah stood framed in the doorway. Cohen, who
saw her every day, realized that she had never looked so radiantly
beautiful before. She had almost burst into the room, but paused as
she saw that a stranger was present.
“Excuse me,” she began; “I had no idea you had a friend with you,
Abraham.”
She would have retreated, but he stopped her with an eager—
“Come in, Zillah.”
She advanced, gazing in curious inquiry at Hammond.
“This is Mr. Tom Hammond, editor of the ‘Courier,’ Zillah,” Cohen
explained to the young girl. To Hammond he added, “My wife’s sister,
Zillah Robart.”
The introduced pair shook hands. The young Jew went on to
explain to Zillah how the great editor came to be visiting him.
Tom Hammond’s eyes were fixed upon the vision of loveliness that
the Jewess made. She was going to assist at the wedding of a girl-
friend, and had come to show herself to her brother-in-law before
starting. Lovely at the most ordinary times, she looked perfectly
radiant in her well-chosen wedding finery.
Tom Hammond had seen female loveliness in many lands—East,
North, West, South. He had gazed upon women who seemed too
lovely for earth—women whose flesh was alabaster, whose glance
would woo emperors; women whose skins glowed with the olive of
southern lands, the glance of whose black, lustrous eyes intoxicated
the beholder in the first instant: Inez of Spain, Mousmee of Japan,
Katrina of Russia, Carlotta of Naples, Rosie of Paris, Maggie of the
Scottish Highlands, Patty of Wales, Kate of Ireland, and a score of
other typical beauties. But this Jewish maiden, this Zillah of Finsbury
—she was beyond all his thought or knowledge of feminine
loveliness.
While Cohen talked on for a moment or two, and Zillah’s eyes
were fixed upon her brother-in-law, Tom Hammond’s gaze was
riveted upon the lovely girl.
Every feature of her beautiful face became photographed on his
brain. Had he been a clever artist, he could have gone to his studio
and have flung with burning, brilliant haste her face upon his canvas.
He thought of Zenobia as he looked upon her brow. He wondered
if ever two such wide, black, lustrous eyes had ever shone in the
face of a woman before, or whether a female soul had ever before
been mirrored in such eyes.
Her mouth was not the large, wide feature so often seen in women
of her race, but of exquisite lines, with ripe, full lips, as brilliant in
colour as the most glowing coral. Her eyes were fringed with the
blackest, finest, silkiest lashes. Her hair was raven in hue and
wondrous in its wealth.
He realized, in that first moment of full gazing upon her, how faded
every other female face must ever seem beside her glorious beauty.
With a strange freak of mental conjuring, Madge Finisterre and that
interrupted tete-a-tete rose up before him, and a sudden sense of
relief swept over him that George Carlyon had returned at the
moment that he did.
“It is all so strange, so wonderful to me, what I have seen and
heard here,” he jerked out as Cohen finished his explanation.
Hammond spoke to the beautiful girl, whose great lustrous eyes
had suddenly come back to his face.
For a moment or two longer he voiced his admiration of the
separate pieces of finished work, and spoke of his own growing
interest in the Jewish race.
The great black eyes that gazed upwards into his, grew liquid with
the evident emotion that filled the soul of the beautiful girl. With the
frank, hearty, simple gesture of the perfectly unconventional woman,
she held forth her hand to Hammond as she said:
“It is so good of you, sir, to speak thus of my brother-in-law’s work
and of our race. There are few who speak kindly of us. Even though,
as a nation, you English give our poor persecuted people sanctuary,
yet there are few who care for us or speak kindly of us, and fewer
still who speak kindly to us.”
Tom Hammond held the pretty, plump little hand that she offered
him clasped warmly in his, almost forgetting himself as he gazed
down into her expressive face and listened to her rich musical voice.
There was an ardency in his gaze that was unknown, unrealized, by
himself.
The olive of the girl’s cheeks warmed under the power of his gaze.
He saw the warm colour rise, and remembered himself, shifted his
eyes, and released her hand.
“I must not stay another moment, Abraham,” she cried, turning to
the Jew. “Adah would be vexed if I were late.”
She turned back to Hammond, but before she could speak he was
saying,
“Good-bye, Miss Robart; I hope we may meet again. What your
brother has already told me only incites me to come again and see
him, for there are many things I want to know.”
He shook hands with the girl again. His eyes met hers, and again
he saw the olive cheeks suddenly warm.
Ten minutes later he was driving back to his office, his mind in a
strange whirl, the beautiful face of Zillah Robart filling all his vision.
He pulled himself up at last, and laughed low and amusedly as he
murmured,
“And I am the man whose pulses had never been quickened by
the sight or the touch of a woman until I met her——”
The memory of Madge Finisterre flashed into his mind. He smiled
to himself as he mused:
“Even when I seemed most smitten by Madge, by her piquant
Americanism, I told myself I was not sure that love had anything to
do with my feelings. Now I know it had not.”
His eyes filled suddenly with a kind of staring wonder as he cried
out, in a low, startled undertone:
“Am I inferring to myself that this sudden admiration for Zillah
Robart has any element of love in it?”
He smiled at his own unuttered answer. The cab pulled up at the
door of the office at that moment. He came back sharply to everyday
things.
CHAPTER XIII.
A DEMON.

Madge Finisterre awoke early on the morning after that discussion


with herself anent Hammond’s possible proposal.
With startling suddenness, as she lay still a moment, a vision of
the pastor of Balhang came up before her mind. Then a strange
thing happened to her, for a yearning sense of home-sickness
suddenly filled her.
She tried to laugh at herself for her “childishness,” as she called it,
and sprang from her bed to prepare for her bath. Standing for one
instant by the bedside, she murmured:
“But, after all, it is time I was paddling across again. Who ever
heard of anyone from our side staying here through the winter? I
must think this all out seriously. Anyway, I’ll get my bath, and dress,
and go for a stroll before breakfast. They say that one ought to see
suburban London pouring over the bridges into London city in the
early morning. I’ll go this morning.”
Half-an-hour later she was dressed ready for her expedition. As
she passed the office on her way out, they were sorting the morning
mail. She waited for her letters. There was only one, but it was from
home.
Racing back to her room, she tore it open with an eagerness born,
unconsciously to herself, of the nostalgia that had seized upon her
three-quarters of an hour before.
There were two large, closely-written sheets in the letter—one
from her father and one from her mother. Each told their own news.
She read her father’s first; every item interested her, though as
she read she seemed to feel that there was all through it an
underlying strain of longing for her return.
“Dear old poppa!” she murmured as she neared the finish of the
epistle.
Suddenly her eyes took in the two lines of postscript jammed close
into the bottom edge of the first sheet. Her heart seemed to stand
still as she read:—
“Pastor is considered sick. Doctor can’t make his case out.”
“Pastor sick!” She gasped the words aloud; then, turning swiftly to
her mother’s letter, she cried: “Momma will tell more than this!”
Her eyes raced over the written lines. Her mother said a little more
than her father had done about the sickness of their friend and
pastor; not much, though, in actual words, but to the disturbed heart
of the young girl there seemed to her much deeper meaning.
An excited trembling came upon her for a few moments. The next
instant she had put a strong curb upon herself, and, folding the
letters, and replacing them in the envelope, she cried out quietly, but
sharply:
“The boat from Southampton sails at two to-day. I’ll catch that!”
The next instant she was divesting herself of her hat and jacket,
and began to set about her packing.
Now and again she talked to herself thus: “Sick, is he? Poor old
pastor! I guess I know what’s the matter with him, and I’ll put him
right in five minutes.”
She smiled as she went on: “I guess, too, I’ve found out what’s the
matter with me—I want to be a pastor’s wife!”
The next instant her voice was carolling out:

“For I tell them they need not come wooing of me,


For my heart, my heart, is over the sea.”

Her fingers were busy, her mind all the time kept mentally
arranging a host of things.
“I wonder,” she murmured presently, “how Uncle Archibald and
George will take my sudden departure? Well, I’m glad George is out
of town. He’s been showing signs of spoons lately with me, so it’s
best, perhaps, that I should get off without seeing him.”

By eleven that forenoon she had left Waterloo. Her uncle had seen
her off from the station. He wanted to accompany her to
Southampton, but she would not hear of it.
“I want to be very quiet all the way down,” she said, “and write
some important letters. Make my excuses to everybody, and explain
that I only had an hour or two to do everything.”
At the last moment her uncle slipped an envelope into her hand,
saying, “You are not to open it until you have been travelling a
quarter of an hour.”
Then came the good-byes, and—off.
She had been travelling nearly a quarter of an hour when she
opened the envelope. There was a brief, hearty, loving note inside, in
her uncle’s hand-writing, expressing the joy her visit had given him,
and his sense of loneliness at her going, and saying:

“Please, dear Madge, accept the enclosure in


second envelope, as a souvenir of your visit, from your
affectionate
“Nunkums.”

She opened the smaller envelope. To her breathless amazement,


she found a Bank of England note for £1,000. When she recovered
herself a little, a smile filled her eyes as she murmured:
“Fancy an American Methodist pastor’s wife with a thousand
pounds of her own! My!”
The train was rushing on; she remembered that she had a special
letter to write. She opened her bag and took out writing materials.
The carriage rocked tremendously, but she managed to pen her
letter. Before she finally enclosed the letter in an envelope, she took
from her purse a two-inch cutting from the columns of some
newspaper or magazine. This she placed in the letter.

Tom Hammond had just settled himself down to work when a


letter, bearing the Southampton post-mark, was delivered to him.
Opening it, and reading “My dear Mr. Hammond,” he turned next to
the signature. “Madge Finisterre?” he cried softly, surprisedly, under
his breath. Wonderingly he turned back to the first page, and read:
“You will be surprised to know that when you receive this I shall be
steaming down Channel en route for New York. I got letters from
home this morning that made it imperative that I should start at once.
“I cannot leave without thanking you for all your kindness to me. It
has been a pleasure to have known you, and I sincerely hope that
we may meet again some day.
“Now I am going to take you right into my confidence, Mr.
Hammond, for who so discreet as a ‘prophet?’—vide ‘The Courier.’
“Yesterday evening, after dinner, I had a long talk alone with
myself. I had had a very pleasant tete-a-tete tea with a friend—
perhaps you may remember this,—and while I went over in mind
many things in connection with that tete-a-tete, especially the events
immediately preceding the interruption, I suddenly realized a sense
of longing for home.
“A night or two before I sailed from America, our pastor asked me
to be his wife. He was awfully in earnest, poor fellow; and I could see
how love for me—gay, frivolous little me—was consuming him. I was
startled at the proposition, and told him frankly that I did not know my
own mind, but that if ever I found out that I loved him, I would come
right away and tell him so. I found out this morning, when I heard
that he was dangerously sick, that I wanted him as much as ever he
wanted me. At this stage of the letter, please read the cutting
enclosed.”
Wondering what the clipping could have to do with the subject,
Tom Hammond laid down the letter and read the cutting:

You might also like