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.
Author(s): Sufyan bin Uzayr
Series: Mastering Computer Science
Edition: 1
Publisher: CRC Press
Year: 2022
Language: English
Pages: 318
Cover
Half Title
Series Page
Title Page
Copyright Page
Table of Contents
Mastering Computer Science Series Preface
About the Editor
Chapter 1 Getting Started with Rust
In This Chapter
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
In This Chapter
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
In This Chapter
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
Syntax
String Slices
Literals Are String Slices
String Slices as Parameters
Other Slices
Chapter 4 Using Structs for Related Data
In This Chapter
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
In This Chapter
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
Matches Are Exhaustive
Catch-all Patterns and the _ Placeholder
Concise Control Flow with if let
Chapter 6 Packages, Crates, and Modules
In This Chapter
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
In This Chapter
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
In This Chapter
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
In This Chapter
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
In This Chapter
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
In This Chapter
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
Sharing Mutex 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
In This Chapter
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
Keywords in Use
Keywords Reserved for the Future Use
Raw Identifiers
Appendix B: Operators and Symbols
Operators
Non-Operator Symbols
Appendix C: Derivable Traits
Debug for Programmer Output
Equality Comparisons with PartialEq and Eq
PartialOrd and Ord for Ordering Comparisons
Clone and Copy for the Duplicating Values
Hash for Mapping a Value to a Fixed Size Value
Default for Default Values
Appraisal
Bibliography
Index