Page
1
(This page has no text content)
Page
2
Problem-solving with algorithms and data structures using Rust Shieber 2023.03.28
Page
3
Preface The emergence of the transistor sparked a revolution in integrated circuits and chips, leading to the development of the central processing unit, large-capacity storage, and convenient communication fa- cilities. Unix [1] was born out of the failure of Multics [2], which subsequently gave rise to the Linux kernel [3] and its various distributions [4]. By combining open source with network technology, the rapid development of IT was made possible. Technological progress provides a platform and tools for prac- tical ideas, while social progress creates new demands and passions, further promoting technological progress. Although the upper layer of the computer world has given rise to the Internet, cloud comput- ing, blockchain, AI, and the Internet of Things, the basic principles underlying the bottom layer remain unchanged. The fundament of computing is the combination of hardware and its abstract data types and algorithms. Whether it’s a regular computer, a supercomputer, or a quantum computer [5], their functions are built on some abstraction of data structures and algorithms. This book focuses on the design, implementation, and use of abstract data types as they play an important role in computer science. By learning to design abstract data types, one can better implement programming and deepen their understanding of them. The algorithm implementations in this book are not the most optimal or general-purpose engineering implementations, as these tend to be verbose and fail to focus on key principles, which can be harmful to learning. Instead, the code in this book takes different simplification measures for different cases, some using generics and others using specific types. These implementation measures are intended to simplify the code and ensure that each segment of code can be compiled and executed separately to obtain a result. Prerequisites Understanding abstract data types does not require specific forms, but implementing code requires consideration of specific forms, which in turn requires a certain level of proficiency in Rust. Although readers’ familiarity with Rust and coding style may vary, the basic requirements remain the same. To read this book, readers should ideally have the following abilities and interests: • Ability to implement complete programs using Rust, including the use of Cargo, rustc, test, etc. • Ability to use basic data types and structures, including structs, enums, loops, matches, etc. • Ability to use Rust generics, lifetimes, ownership system, pointers, unsafe code, macros, etc. • Ability to use built-in libraries (crates) and external libraries, and to set up Cargo.toml. If readers lack these abilities, they can refer to the section on Rust learning materials in Chapter 1 and find some recommended books and resources to learn Rust first, before returning to this book. The code for this book is available on Github, organized according to chapter and name. Readers are welcome to download and use it, and to point out any errors they find. This book and all code were written in the Ubuntu 20.04 environment, with Rust version 1.58. The code environment has two types: code with and without line numbers. The former is used to show code, while the latter displays results or other content. All code except for simple or explanatory code, which does not give results, provides outputs. Shorter outputs are commented within the current code box, while more complex outputs are placed in a code box without line numbers. 1
Page
4
Preface Whole Book Structure To provide readers with a clear understanding of the structure of the book and to help advanced users select chapters, we have summarized the contents of the entire book below. The book is divided into ten chapters. Chapter 1 organizes Rust learning materials and reviews basic knowledge. Chapters 2 and 3 introduce the concepts of computer science and algorithm analysis, forming the foundation of the book. Chapters 4 to 7 cover the design and implementation of simple data structures and algorithms, while Chapters 8 and 9 cover more complex tree and graph data structures, which are widely used. These two chapters build upon the higher-level topics covered in the previous chapters. The final chapter contains several practical projects that use the data structures and algorithms to solve real problems. Readers are encouraged to start with the first three chapters and then progress through the middle chapters and practical project in order. However, readers can also choose to learn certain chapters first and then learn other content. Chapter 1: Rust Basics. This chapter covers the basics of Rust, including installation of the Rust toolchain, organization of Rust learning resources, a review of Rust fundamentals, and a project. Readers who are already familiar with these topics can choose to skip this chapter. The final project summarizes the learned basic knowledge and demonstrates how Rust modules and code are organized. Chapter 2: Computer Science. This chapter introduces the definition and concepts of computer sci- ence, which can help readers analyze real problems. This includes establishing abstract data type models for data structures, designing and implementing algorithms, and verifying algorithm performance. Ab- stract data types describe the logic of data operations and hide implementation details, which better abstracts the essence of the problem. Chapter 3: AlgorithmAnalysis. Algorithm analysis is amethod for understanding program execution time and space performance, and can help determine algorithm performance efficiency. The standard method of algorithm analysis is the Big-O notaion analysis. Chapter 4: Basic Data Structures. This chapter covers basic data structures in Rust. These data structures include arrays, slices, Vec, and derivative stacks, queues, and more which are based on the linear memory model. The chapter focuses on using Vec to implement these basic data structures. Chapter 5: Recursion. Recursion is an algorithmic technique that is another form of iteration. It must satisfy the three laws of recursion, and tail recursion is an optimization of recursion. Dynamic program- ming is an efficient algorithmic technique, which can be implemented using recursion or iteration. Chapter 6: Search. This chapter covers search algorithms that are used to find elements in a data set or to determine if an element exists. Sequential and non-sequential search algorithms are explained based on whether the data set is ordered or not. Chapter 7: Sorting. In the previous chapter, the sequential search algorithm required ordered data, but data is generally unordered. Thus, sorting algorithms are needed. This chapter covers ten com- mon sorting algorithms, including bubble sort, quick sort, insertion sort, shell sort, merge sort, selection sort, heap sort, bucket sort, counting sort, and radix sort. Tim sort algorithm, a combination of some common sorting algorithms which is very efficient, has become the default sorting algorithm in many programming languages. Chapter 8: Trees. This chapter explains how non-linear data structures can be constructed on linear systems. Trees are non-linear data structures that point to subtrees through pointers or references. Binary trees, binary heaps, binary search trees and balanced binary trees are explained. B-trees, B+ trees, and red-black trees are more complex trees. Chapter 9: Graphs. Unlike trees, graphs have no parent-child node relationship and have connections that can go in any direction. This chapter explains how graphs, a non-linear data structure, are used to handle problems with a large number of nodes and connections, such as network traffic, and path searching. Graph storage forms, including adjacency lists and adjacency matrices, are also explained. Chapter 10: Practical Projects. This chapter applies the knowledge we learned in the previous chap- ters to solve practical problems. Distance algorithms, trie, filters, cache eviction algorithms, consistent hashing algorithms, and blockchain are covered. These practical projects help readers deepen their un- derstanding of data structures and improve their Rust coding skills. 2
Page
5
Preface Acknowledgments Rust is an excellent language that provides efficient, secure, and convenient engineeringmanagement tools, and it is gradually being integrated into the Linux kernel, making it a potential replacement for some C/C++ work in the future. Although several Rust books are available in the market, the author noticed that there are no algorithm books about Rust, which led to many obstacles in the learning process. Therefore, the author decided to create a simple and convenient Rust book that can help newcomers learn algorithms and data structures. After extensive research [6], thinking, organizing, and combining the author’s learning experience, this book was completed. Despite the steep learning curve of Rust, with the right direction and good resources, one can learn the language well. The author hopes that this book will make a small contribution to the Rust learning community. The primary aim of writing this book is to learn and promote Rust and give back to the entire open- source community, which has enabled the author to learn and grow. The author expresses gratitude to PingCap for developing TiDB, the operating open-source community, and online courses. The author also thanks Zhang Handong, Mike Tang and other members of the Rust Chinese community for orga- nizing Rust conferences and maintaining the community, Ling Hu Yi Chong for sharing Rust learning videos on Bilibili Danmu website, Zhang Handong for promoting Rust language through his book, ”The Tao of Rust Programming,” and RustMagazine Chinese monthly. The author also acknowledges the Rust Foundation [7], established by Mozilla, AWS, Facebook, Google, Microsoft, and Huawei, for creating a platform that motivates the author to write this book, given the shortage of learning resources. Finally, the author thanks the University of Electronic Science and Technology of China(UESTC) for providing resources and environment and the care and help of the author’s mentor and fellow students in the KC404 teaching and research section where the author learned various technologies and cultures, grew up, and found the direction for his life journey. S h i e b e r 3
Page
6
Contents Preface 1 1 Rust Basic 1 1.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1.2 Install Rust and its Toolchain . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1.3 Learning Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 1.3.1 Books and Documents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 1.3.2 Related Topics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 1.3.3 Community and Blogs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 1.4 Review . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 1.4.1 The History of Rust . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 1.4.2 Keywords, Comments, Naming conventions . . . . . . . . . . . . . . . . . . . . 4 1.4.3 Constants, Variables, Data Type . . . . . . . . . . . . . . . . . . . . . . . . . . 6 1.4.4 Statement, Expression, Computors and Flow Control . . . . . . . . . . . . . . . 10 1.4.5 Function, Program Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 1.4.6 Ownership, Scope, Lifetime . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 1.4.7 Generic, Trait . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 1.4.8 Enum and Match . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 1.4.9 Functional Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 1.4.10 Smart Pointer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 1.4.11 Exception . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 1.4.12 Macro . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 1.4.13 Code Organization and Dependency . . . . . . . . . . . . . . . . . . . . . . . . 35 1.4.14 Project: a password generator . . . . . . . . . . . . . . . . . . . . . . . . . . . 37 1.5 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44 2 Computer Science 45 2.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 2.2 Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 2.3 What is Computer Science? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 2.4 What is Programming? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46 2.5 Why Study Data Structures and Abstract Data Types? . . . . . . . . . . . . . . . . . . . 47 2.6 Why Study Algorithms? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47 2.7 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48 3 Algorithm Analysis 49 3.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49 3.2 What is Algorithm Analysis? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49 3.3 Big-O Notation Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51 3.4 Anagram Detection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54 3.4.1 Brute Force . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
Page
7
CONTENTS CONTENTS 3.4.2 Checking Off . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54 3.4.3 Sort and Compare . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56 3.4.4 Count and Compare . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57 3.5 Performance of Rust Data Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58 3.5.1 Scalar and Complex Data Structures . . . . . . . . . . . . . . . . . . . . . . . . 58 3.5.2 Collection Data Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58 3.6 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59 4 Basic Data Structures 60 4.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60 4.2 Linear Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60 4.3 Stack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60 4.3.1 The Stack Abstract Data Type . . . . . . . . . . . . . . . . . . . . . . . . . . . 62 4.3.2 Implemeting a Stack in Rust . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62 4.3.3 Simple Balanced Parentheses . . . . . . . . . . . . . . . . . . . . . . . . . . . 66 4.3.4 Converting Decimal Numbers to Binary Numbers . . . . . . . . . . . . . . . . . 70 4.3.5 Prefix, Infix, Postfix Expressions . . . . . . . . . . . . . . . . . . . . . . . . . 72 4.3.6 Conversion of Infix Expressions to Prefix and Postfix . . . . . . . . . . . . . . . 74 4.4 Queue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80 4.4.1 The Queue Abstract Data Type . . . . . . . . . . . . . . . . . . . . . . . . . . . 80 4.4.2 Implementing a Queue in Rust . . . . . . . . . . . . . . . . . . . . . . . . . . . 81 4.4.3 Hot Potato . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84 4.5 Deque . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85 4.5.1 The Deque Abstract Data Type . . . . . . . . . . . . . . . . . . . . . . . . . . . 86 4.5.2 Implementing a Deque in Rust . . . . . . . . . . . . . . . . . . . . . . . . . . . 87 4.5.3 Palindrome Checker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91 4.6 LinkedList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92 4.6.1 The LinkedList Abstract Data Type . . . . . . . . . . . . . . . . . . . . . . . . 92 4.6.2 Implementing a LinkedList in Rust . . . . . . . . . . . . . . . . . . . . . . . . 93 4.6.3 LinkedList Stack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97 4.7 Vec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101 4.7.1 The Vec Abstract Data Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101 4.7.2 Implementing a Vec in Rust . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101 4.8 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107 5 Recursion 108 5.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108 5.2 What is Recursion? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108 5.2.1 The Three Laws of Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . 110 5.2.2 Converting an Integer to a String in Any Base . . . . . . . . . . . . . . . . . . . 111 5.2.3 Tower of Hanoi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113 5.3 Tail Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114 5.3.1 Recursion VS Iteration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115 5.4 Dynamic Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116 5.4.1 What is Dynamic Programming? . . . . . . . . . . . . . . . . . . . . . . . . . . 119 5.4.2 Dynamic Programming VS Recursion . . . . . . . . . . . . . . . . . . . . . . . 121 5.5 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
Page
8
CONTENTS CONTENTS 6 Searching 123 6.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123 6.2 What is Searching? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123 6.3 The Sequential Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123 6.3.1 Implementing an Sequential Search in Rust . . . . . . . . . . . . . . . . . . . . 124 6.3.2 Analysis of Sequential Search . . . . . . . . . . . . . . . . . . . . . . . . . . . 125 6.4 The Binary Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127 6.4.1 Implementing a Binary Search . . . . . . . . . . . . . . . . . . . . . . . . . . . 127 6.4.2 Analysis of Binary Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129 6.4.3 The Interpolation Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130 6.4.4 The Exponential Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131 6.5 The Hash Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132 6.5.1 Hash Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133 6.5.2 Collison Resolution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135 6.5.3 Implementing a HashMap in Rust . . . . . . . . . . . . . . . . . . . . . . . . . 137 6.5.4 Analysis of HashMap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143 6.6 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144 7 Sorting 145 7.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145 7.2 What is Sorting? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145 7.3 The Bubble Sort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146 7.4 The Quick Sort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151 7.5 The Insertion Sort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155 7.6 The Shell Sort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158 7.7 The Merge Sort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159 7.8 The Selection Sort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162 7.9 The Heap Sort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163 7.10 The Bucket Sort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166 7.11 The Counting Sort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169 7.12 The Radix Sort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170 7.13 The Tim Sort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172 7.14 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185 8 Trees 186 8.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186 8.2 What is Tree? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186 8.2.1 Vocabularies and Definitions of Tree . . . . . . . . . . . . . . . . . . . . . . . . 189 8.2.2 Tree Representation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190 8.2.3 Parse Tree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194 8.2.4 Tree Traversals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195 8.3 Binary Heap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202 8.3.1 The Binary Heap Abstract Data Type . . . . . . . . . . . . . . . . . . . . . . . 202 8.3.2 Implementing a Binay Heap in Rust . . . . . . . . . . . . . . . . . . . . . . . . 203 8.3.3 Analysis of Binary Heap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210 8.4 Binary Search Tree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210 8.4.1 The Binary Search Tree Abstract Data Type . . . . . . . . . . . . . . . . . . . . 210 8.4.2 Implementing a Binary Search Tree in Rust . . . . . . . . . . . . . . . . . . . . 211 8.4.3 Analysis of Binary Search Tree . . . . . . . . . . . . . . . . . . . . . . . . . . 222 8.5 Balanced Binary Search Tree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222 8.5.1 AVL Tree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223 8.5.2 Implementing a AVL Tree in Rust . . . . . . . . . . . . . . . . . . . . . . . . . 224
Page
9
CONTENTS CONTENTS 8.5.3 Analysis of AVL Tree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236 8.6 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236
Page
10
Chapter 1 Rust Basic 1.1 Objectives • Install Rust and learn its toolchain • Explore learning resources for Rust in various areas • Review the fundamentals of the Rust programming language 1.2 Install Rust and its Toolchain Ubuntu 22.04 and later versions come with pre-installed Rust, so you can start using it right away. If you’re using other Unix-like systems, use the command below to install Rust. For Windows, refer to the official website. As the code in this book is written in Linux, we recommend readers use Linux or Mac OS to avoid any inconsistencies and errors caused by different environments. $ curl --proto '=https' --tlsv1.2 \ -sSf https://sh.rustup.rs | sh After installing Rust on Linux, you need to set environment variables to enable the system to locate Rust tools like the rustc compiler. Add the following three lines to the end of ~/.bashrc. # Rust env-path variables export RUSTPATH=$HOME/.cargo/bin export PATH=$PATH:$RUSTPATH Then, save and execute source ~/.bashrc. If you find this process cumbersome, you can download the install_rust.sh script from the first chapter of the source code of this book and run it to complete the Rust toolchain installation. The instructions above will install the rustup tool, which manages and installs the Rust toolchain, including the rustc compiler, cargo project management tool, rustup toolchain management tool, rustdoc documentation tool, rustfmt formatting tool, and rust-gdb debugging tool. For simple projects, you can use the rustc compiler for compilation. However, for larger projects, you need the cargo tool for management, which internally calls rustc for compilation. Cargo is an excel- lent tool that handles project building, testing, compilation, and publishing, making it highly efficient. Programmers who have worked with C/C++ projects will appreciate the cargo tool’s greatness in han- dling various libraries and dependencies. Most of the time, we use the rustc compiler instead of the cargo tool, as the projects in this book are not too complex. Rustup manages the installation, upgrade, and uninstallation of Rust tools. Note that the Rust language includes stable and nightly versions, both of which can coexist. You can install Nightly using the following command. 1
Page
11
1.3. LEARNING RESOURCES CHAPTER 1. RUST BASIC $ rustup default nightly After installation, you can use rustup to check the current version in use. $ rustup toolchain list stable-x86_64-unknown-linux-gnu nightly-x86_64-unknown-linux-gnu (default) To switch between stable and nightly versions, please use the following command. $ rustup default stable # nightly 1.3 Learning Resources Rust is a systems programming language and has a certain level of difficulty. It is impossible to learn Rust without good resources. Below is a collection of learning materials in various fields of Rust compiled by the author. It may not be complete, but most fields are covered. 1.3.1 Books and Documents Basic: The Rust Programming Language, Easy to Understand Rust, Rustlings, Rust by Example, Rust Primer, Rust Cookbook, Rust in Action, Rust Course Advanced: Cargo Documentation, The Tao of Rust Programming, Learn Rust With Entirely Too Many Linked Lists, Rust Design Patterns High-level: rustc book, The Little Book of Rust Macros, The Rustonomicon, Asynchronous Program- ming in Rust 1.3.2 Related Topics Wasm: https://wasmer.io, https://wasmtime.dev, https://wasmedge.org HTTP/3: https://github.com/cloudflare/quiche Algorithms: https://github.com/TheAlgorithms/Rust Games: https://github.com/bevyengine/bevy Tools: https://github.com/rustdesk/rustdesk, https://github.com/uutils/coreutils Blockchain: https://github.com/w3f/polkadot Databases: https://github.com/tikv, https://github.com/tensorbase/tensorbase Compilers: https://github.com/rust-lang/rustc_codegen_gcc Operating Systems: https://github.com/Rust-for-Linux, https://github.com/rcore-os Web Front-end: https://github.com/yewstack/yew, https://github.com/denoland/deno WebBack-end: https://actix.rs/, https://github.com/tokio-rs/axum, https://github.com/poem-web/poem 1.3.3 Community and Blogs Rust Official: https://www.rust-lang.org Rust Source Code: https://github.com/rust-lang/rust Rust Documentation: https://doc.rust-lang.org/stable Rust Reference: https://doc.rust-lang.org/reference Awesome Rust: https://github.com/rust-unofficial/awesome-rust Rust lib/crate: https://crates.io, https://lib.rs Rust Sources: https://www.yuque.com/zhoujiping/programming/rust-materials Rust Cheat Sheet: https://cheats.rs 2
Page
12
1.4. REVIEW CHAPTER 1. RUST BASIC 1.4 Review Similar to C/C++, Rust is a systems programming language. This means that concepts learned in those languages can be applied to understand Rust better. However, Rust introduces unique concepts like mutability, ownership, borrowing, and lifetimes, which can be both advantages and challenges. 1.4.1 The History of Rust Rust is a highly efficient and reliable general-purpose compiled language that utilizes LLVM as its backend. It offers a balance between development efficiency and execution efficiency, making it a pop- ular language among developers. The language has consistently been ranked as the most loved language by developers on Stack Overflow for many years. In 2021, Google, Amazon, Huawei, Microsoft, and Mozilla established a foundation for Rust, and Google even funded the rewriting of the Internet infras- tructure Apache httpd and OpenSSL in Rust. Rust also has its own mascot, a red crab named Ferris. Rust was originally a personal project of Mozilla employee Graydon Hoare, and it received support from the Mozilla Research Institute starting in 2009. Rust was released to the public in 2010. Mozilla supported Rust because the Firefox Gecko engine was behind the times due to various vulnerabilities, historical baggage, and performance bottlenecks. Rust replaced the OCaml-written compiler implemen- tation for self-hosting in 2010-2011 and released version 1.0 in 2015. Rust has a strong and active community, and a stable and testing version are released every six weeks, with a major edition released every three years. Rust employs modern engineering management tool Cargo and has over 100,000 packages published on crates.io. In addition to development efficiency, Rust also exhibits excellent performance. In 2017, a team of six Portuguese researchers conducted a survey [8] on the performance of various programming languages, and Rust was found to be highly performant. They wrote solutions to ten problems based on 27 languages using the same algorithm, and then ran these solutions, recording the electricity consumption, speed, and memory usage of each language. 3
Page
13
1.4. REVIEW CHAPTER 1. RUST BASIC The figure above provides readers with a clear understanding of the resource usage of various pro- gramming languages. Rust’s energy consumption, time consumption, and memory consumption indica- tors are all very favorable. While this comparison may not be completely accurate, the overall trend is clear: Rust is energy-saving and efficient. Considering the critical point of climate change we currently face, the use of energy-saving and efficient languages like Rust to develop software is in line with the trend of Carbon Peaking and Carbon Neutrality Goals. I believe that it can be an important tool for enterprise transformation and look forward to the industry and society reaching a consensus. Rust has a wide range of applications that extends to command-line tools, DevOps tools, audio and video processing, game engines, search engines, blockchain, the Internet of Things, browsers, cloud- native, network servers, databases, and operating systems. Many universities and enterprises at home and abroad are using Rust extensively. For example, Tsinghua University uses Rust in its new students’ rCore and zCore operating systems, ByteDance’s Feishu, remote desktop software RustDesk, PingCap’s TiDB database, js/ts runtime Deno, and Google’s Fuchsia operating system. 1.4.2 Keywords, Comments, Naming conventions Rust uses 39 keywords (which may increase in the future), and some of these keywords, such as Self and self, can be challenging to learn. Self enum match super as extern mod trait async false move true await fn mut type break for pub union const if ref unsafe continue impl return use crate in self where dyn let static while else loop struct Keywords are crucial to programming languages and reflect the designers’ thought process behind program design. Different keywords indicate different trade-offs and considerations for various tasks. For instance, Rust’s match is powerful, while C’s similar switch functionality is less so, resulting in different coding styles and ways of thinking. To facilitate code understanding and explain complex logic, appropriate explanations must be pro- vided within the program. Comments serve as a useful place for these explanations. Rust supports two types of comments: regular comments and documentation comments. Regular comments have three comment formats. 1 // comment style 1 2 3 /* comment style 2 */ 4 5 /* 6 * comment style 3 7 * multi-line-comments 8 * multi-line-comments 9 * multi-line-comments 10 */ Documentation and testing are highly emphasized in Rust, which is why it features a special doc- umentation comment feature. This feature enables the writing of documentation and test code within comments, allowing code testing through cargo test and document generation through cargo doc. 4
Page
14
1.4. REVIEW CHAPTER 1. RUST BASIC 1 //! This symbol placed at the top of a module file to control 2 //! the generation of library documentation and to describe 3 //! the functionality of the entire module. 4 /// This symbol is placed above the object being described to 5 /// control the generation of library documentation and to 6 /// describe functions or structures. Rust’s documentation uses Markdown syntax, so using the # symbol is essential. 1 //! Math mod <-- doc comment, describe mode 2 //! 3 /// # Add <-- doc comment, discribe function, test case 4 /// This function sum the inputs 5 /// 6 /// # Example <-- test code, use case 7 /// use math::add; 8 /// assert_eq!(3, add(1, 2)); 9 fn add(x: i32, y: i32) -> i32 { 10 // sum <-- regular comment 11 x + y 12 } Naming conventions have been a topic of interest in programming, and Rust has its recommended practices. Rust suggests using UpperCamelCase for class-level content and snake_case for value-level content. Item Convention Crate snake_case Type UpperCamelCase Trait UpperCamelCase Enum UpperCamelCase Function snake_case Method snake_case Constructor new / with_more_details Converter from_other_type Macros snake_case! Local variable snake_case Static variable SCREAMING_SNAKE_CASE Constants SCREAMING_SNAKE_CASE Type Param The alphabeta of UpperCamelCase, like T, U, K Lifetime lowercase,such as 'a, 'src, 'dest In UpperCamelCase, initialisms and abbreviations of compound words count as one word. For ex- ample, Usize should be used instead of USize. In snake_case or SCREAMING_SNAKE_CASE, words should not be composed of single letters unless it is the last word. Therefore, btree_map should be used instead of b_tree_map, and PI_2 instead of PI2. The following code exemplifies Rust’s naming conventions, which this book follows, and readers are encouraged to follow as well. 1 // Enum 2 enum Result<T, E> { 3 Ok(T), 4 Err(E), 5 } 5
Page
15
1.4. REVIEW CHAPTER 1. RUST BASIC 6 7 // Trait 8 pub trait From<T> { 9 fn from<T> -> Self; 10 } 11 12 // Struct 13 struct Rectangle { 14 height: i32, 15 width: i32, 16 } 17 impl Rectangle { 18 // constructor 19 fn new(height: i32, width: i32) -> Self { 20 Self { height, width } 21 } 22 23 // function 24 fn calc_area(&self) -> i32 { 25 self.height * self.width 26 } 27 } 28 29 // static and constant variables 30 static NAME: &str = "kew"; 31 const AGE: i32 = 25; 32 33 // Macro definition 34 macro_rules! add { 35 ($a:expr, $b:expr) => { 36 { 37 $a + $b 38 } 39 } 40 } 41 42 // variable and macro call 43 let sum_of_nums = add!(1, 2); As Rust’s popularity grows and its usage expands, a unified coding standard becomes necessary. Currently, Professor Zhang Handong leads a good Rust Coding Standard, which readers can refer to. 1.4.3 Constants, Variables, Data Type Variables and constants are fundamental concepts in programming, and Rust is no exception. How- ever, Rust introduces mutability and immutability, which can be confusing, especially for beginners transitioning from other programming languages. In Rust, there are three types of values: constants, vari- ables, and static variables. Novices may face difficulties when dealing with mutability and immutability, and they may have to struggle with the compiler to get their code to compile. By understanding the dif- ferences between constants, variables, and static variables, Rust programmers can write more concise and efficient code. Constants are defined using const and are bound to a name that cannot be changed or reassigned. 6
Page
16
1.4. REVIEW CHAPTER 1. RUST BASIC 1 // define constant(like #define used in C/C++) 2 const AGE: i32 = 1984; 3 // AGE = 1995; error, mutation not allowed 4 5 const NUM: f64 = 233.0; 6 // const NUM: f64 = 211.0; error, defined Variables are defined using let and can have a value that is mutable or immutable depending on whether mut is used during its definition. 1 let x: f64 = 3.14; // let defines x which can be reassigned 2 // but not mutated. 3 // x = 6.28; error, x is unmutable 4 let x: f64 = 2.71 // reassign x 5 6 let mut y = 985; // let mut defines y which can be reassigned 7 // and mutated. 8 y = 996; // y is mutable 9 let y = 2019; // reassign y Finally, static variables are defined using static and can be mutable or immutable depending on whether mut is used during its definition. 1 static NAME: &str = "shieber" // static variable which can be 2 // used as a constant 3 // NAME = "kew"; error,NAME is unmutable 4 5 static mut NUM: i32 = 100; // static mutable variable 6 unsafe { 7 NUM += 1; // NUM is mutable 8 println!("Num:{}",NUM); 9 } The ”mut” keyword is a constraint in Rust programming, restricting variables from being changed unless ”mut” is added in front of it. Otherwise, the variable is immutable. This differs from other programming languages. Although static variables and constants have similarities, they’re different in reality. Constants are replaced inline as many times as they’re used, while static variables are referenced, with only one global instance. Static variables defined with ”static mut” are wrapped in ”unsafe” to indicate that they’re not safe. It’s recommended to use constants and variables instead, forget about static variables, and avoid coding errors. Data types are the building blocks of a language, and Rust’s data types are similar to C, while some are similar to Go. There are two types of basic data types in Rust: scalar and compound. Scalar types represent a single value, such as integers, floating-point numbers, Boolean types, and character types. Compound types combine multiple values into one, such as tuples and arrays, which are Rust’s two native compound types. Integers in Rust are numbers without a decimal part, classified into 12 types based on whether they’re signed or unsigned and their length, denoted by ”i” for signed types and ”u” for unsigned types. A 64-bit machine can handle a 128-bit number by storing it in segments and processing it using multiple registers. ”isize” and ”usize” are integer types that match the machine architecture. So on a 64-bit machine, ”isize” and ”usize” represent ”i64” and ”u64,” respectively. On a 32-bit machine, they represent ”i32” and ”u32.” Size Signed Unsigned 8 i8 u8 7
Page
17
1.4. REVIEW CHAPTER 1. RUST BASIC 16 i16 u16 32 i32 u32 64 i64 u64 128 i128 u128 arch isize usize Floating-point numbers in Rust are numbers with a decimal part, having two types: ”f32” and ”f64,” with the default type being ”f64,” and both types being signed. Size Signed 32 f32 64 f64 (default) The boolean type in Rust is represented by ”bool” and has only two values: true and false, consistent with other programming languages. The character type ”char” in Rust is the most primitive type, similar to the C language. Characters are declared using single quotes, while string literals are declared using double quotes. The variables ”c” and ”c_str” are completely different types, with characters being four-byte Unicode scalar values, and strings represented as arrays. 1 // unicode scalar value 2 let c = 's'; 3 4 // dynamic arrays 5 let c_str = "s"; Tuples are a type of composite value that combines multiple values of other types. Once declared, the length of a tuple cannot be increased or decreased. Tuples use parentheses to enclose the values, separated by commas. To retrieve values from a tuple, pattern matching and dot notation can be used, with indices starting at 0. 1 let tup1: (i8, f32, i64) = (-1, 2.33, 8000_0000); 2 // pattern match 3 let (x, y, z) = tup1; 4 5 let tup2 = (0, 100, 2.4); 6 let zero = tup2.0; // use symbol . to get value 7 let one_hundred = tup2.1; In Rust, the let keyword is not just used to define variables, but can also destructure values through pattern matching. For example, x, y, and z can each obtain the values of -1, 2.33, and 80000000, re- spectively, through pattern matching. Defining variables is also a form of pattern matching, as let is essentially a pattern matching operation. The unit type in Rust is represented by an empty tuple (), and when there is only one value, it is written as (). The unit value is a special value of this type, and is implicitly returned when an expression does not return any value. Unlike tuples, arrays in Rust must have elements of the same type, and the length cannot be changed once declared. If a mutable collection is needed, Vec can be used instead. It allows for dynamic resizing and is the preferred option in most situations. 1 // define arrays 2 let genders = ["Female", "Male", "Bigender"]; 3 let gender_f = genders[0]; // indice element 4 5 // [type; num] define array 8
Page
18
1.4. REVIEW CHAPTER 1. RUST BASIC 6 let digits[i32; 5] = [0, 1, 2, 3, 4]; 7 let zeros = [0; 10]; // define an array which holds ten '0' Rust allows for explicit type conversion between data types using the as keyword, but does not provide implicit type conversion between primitive types. Integer conversions in Rust follow the con- ventions of the C language, and all integer conversions are well-defined. For instance, converting i8 to i32 is a reasonable conversion that can be done explicitly. 1 // type_transfer.rs 2 #![allow(overflowing_literals)] // Ignore overflow warnings 3 // for type conversion. 4 fn main() { 5 let decimal = 61.3214_f32; 6 // let integer: u8 = decimal; // Error, f32 cannot be 7 // converted to u8. 8 let integer = decimal as u8; // Correct, use as 9 let character = integer as char; 10 println!("1000 as a u16: {}", 1000 as u16); 11 println!("1000 as a u8: {}", 1000 as u8); 12 } For some complex types, Rust also provides two traits, From and Into, for conversion. 1 pub trait From<T> { 2 fn from<T> -> Self; 3 } 4 pub trait Into<T> { 5 fn into<T> -> T; 6 } With these two traits, you can provide conversion functionality for various types. 1 // integer_to_complex.rs 2 #[derive(Debug)] 3 struct Complex { 4 real: i32, // real quantity 5 imag: i32 // imaginary quantity 6 } 7 8 // Implement a conversion from i32 to a complex number, where 9 // the i32 is converted to the real part and the imaginary 10 // part is set to 0. 11 impl From<i32> for Complex { 12 fn from(real: i32) -> Self { 13 Self { real, imag: 0 } 14 } 15 } 16 17 fn main() { 18 let c1: Complex = Complex::from(2_i32); 19 // implemented Into by default 20 let c2: Complex = 2_i32.into(); 21 println!("c1: {:?}, c2: {:?}", c1, c2); 22 } 9
Page
19
1.4. REVIEW CHAPTER 1. RUST BASIC 1.4.4 Statement, Expression, Computors and Flow Control In Rust, there are two basic syntax categories: Statements and Expressions. Statements refer to operations to be executed, while expressions are simply used to evaluate values. Rust statements include declaration statements and expression statements. Declaration statements are used to declare variables, static variables, constants, structs, functions, external packages, and external modules. Statements that end with a semicolon are expression statements. 1 // Declaration statement for function 2 fn sum_of_nums(nums: &[i32]) -> i32{ 3 nums.iter().sum::<i32>() 4 } 5 6 let x = 5; // The entire line is a statement, x = 5 is an 7 // expression that calculates the value of x 8 x + 1; // The entire line is an expression 9 let y = x + 1; // The entire line is a statement, y = x + 1 10 // is an expression 11 println!("{y}"); 12 13 let z = [1,2,3]; 14 println!("sum is {:?}", sum_of_nums(&z)); Operators are symbols used to specify the type of calculation performed by an expression. Rust supports common types of operators including arithmetic, relational, logical, assignment, and reference operators. Here are some Rust operators and their functions: Operator Example Explanation + expr + expr addition + trait + trait, 'a + trait compound type constraint - expr - expr subtraction - - expr negation * expr * expr multiply * *expr dereference * *const type, *mut type raw pointer / expr / expr division % expr % expr remainder = var = expr, ident = type asignmen/equality += var += expr addition and assignment -= var -= expr subtraction and assignment *= var *= expr multiply and assignment /= var /= expr division and assignment %= var %= expr remainder and assignment == expr == expr equality comparison != var != expr inequality comparison > expr > expr greater-than comparison < expr < expr less-than comparison >= expr >= expr >= comparison <= expr <= expr <= comparison && expr && expr logical AND || expr || expr logical OR ! !expr bitwise NOT or logical NOT 10
Page
20
1.4. REVIEW CHAPTER 1. RUST BASIC & expr & expr bitwise AND & &expr, &mut expr borrow & &type, &mut type, pointer/reference | pat | pat pattern matching | expr | expr bitwise OR ^ expr ^ expr bitwise XOR << expr << expr left shift >> expr >> expr right shift &= var &= expr bitwise AND and assignment |= var |= expr bitwise OR and assignment ^= var ^= expr bitwise XOR and assignment <<= var <<= expr left shift and assignment >>= var >>= expr right shift and assignment . expr.ident member access .. .., expr.., ..expr, expr..expr right-exclusive range .. ..expr struct update syntax ..= ..=expr, expr..=expr right-inclusive range : pat: type, ident: type type constraint : ident: expr struct field initialization : 'a: loop {...} loop label ; [type; len] fixed-size array type => pat => expr match arm @ ident @ pat pattern binding ? expr? error propagation -> fn(...) -> type, |...| -> type function or closure return type The ability to decide whether to execute a piece of code based on a condition or to repeatedly run a piece of code depending on whether a condition is satisfied is a feature found in most programming languages. In Rust, if expressions and loops are the most common structures used to control execution flow. 1 let a = 3; 2 3 if a > 5 { 4 println!("Greater than 5"); 5 } else if a > 3 { 6 println!("Greater than 3"); 7 } else { 8 println!("less or equal to 3"); 9 } if and let can also be combined to control code execution. One way to do this is with a let if statement, which returns the result to the let section if the condition is met. Note that there is a semicolon at the end because let c = ..; is a statement. 1 let a = 3; let b = 2; 2 let c = if a > b { 3 true 11