43,19 €
Design and implement professional-level programs by leveraging modern data structures and algorithms in Rust
Key Features:
Improve your productivity by writing more simple and easy code in RustDiscover the functional and reactive implementations of traditional data structuresDelve into new domains of Rust, including WebAssembly, networking, and command-line tools
Book Description:
Rust is a powerful language with a rare combination of safety, speed, and zero-cost abstractions. This Learning Path is filled with clear and simple explanations of its features along with real-world examples, demonstrating how you can build robust, scalable, and reliable programs.
You’ll get started with an introduction to Rust data structures, algorithms, and essential language constructs. Next, you will understand how to store data using linked lists, arrays, stacks, and queues. You’ll also learn to implement sorting and searching algorithms, such as Brute Force algorithms, Greedy algorithms, Dynamic Programming, and Backtracking. As you progress, you’ll pick up on using Rust for systems programming, network programming, and the web. You’ll then move on to discover a variety of techniques, right from writing memory-safe code, to building idiomatic Rust libraries, and even advanced macros.
By the end of this Learning Path, you’ll be able to implement Rust for enterprise projects, writing better tests and documentation, designing for performance, and creating idiomatic Rust code.
This Learning Path includes content from the following Packt products:
Mastering Rust - Second Edition by Rahul Sharma and Vesa KaihlavirtaHands-On Data Structures and Algorithms with Rust by Claus Matzinger
What you will learn:
Design and implement complex data structures in RustCreate and use well-tested and reusable components with RustUnderstand the basics of multithreaded programming and advanced algorithm designExplore application profiling based on benchmarking and testingStudy and apply best practices and strategies in error handlingCreate efficient web applications with the Actix-web frameworkUse Diesel for type-safe database interactions in your web application
Who this book is for:
If you are already familiar with an imperative language and now want to progress from being a beginner to an intermediate-level Rust programmer, this Learning Path is for you. Developers who are already familiar with Rust and want to delve deeper into the essential data structures and algorithms in Rust will also find this Learning Path useful.
Rahul Sharma is passionately curious about computer science and programming. A believer in Mozilla’s vision of an Open Web, Rahul currently works at AtherEnergy where he builds a resilient cloud infrastructure for smart scooters. His interests include systems programming, real-time web technologies, compilers, and type theory. He is also an occasional contributor to the Rust language. He also contributes and mentors interns on the Servo project by Mozilla. Vesa Kaihlavirta has been programming since he was five, beginning with C64 Basic. His main professional goal in life is to increase awareness of programming languages and software quality in all industries that use the software. He's an Arch Linux Developer Fellow and has been working in the telecom and financial industry for a decade. Claus Matzinger is a software engineer with a very diverse background. After working in a small company maintaining code for embedded devices, he joined a large corporation to work on legacy Smalltalk applications. This led to a great interest in programming languages early on, and Claus became the CTO for a health games start-up based on Scala technology. Since then, Claus' roles have shifted toward customer-facing roles in the IoT database-technology start-up crate.io and, most recently, Microsoft. There, he hosts a podcast, writes code together with customers, and blogs about the solutions arising from these engagements. For more than 5 years, Claus has implemented software to help customers innovate, achieve, and maintain success.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 849
Veröffentlichungsjahr: 2019
Copyright © 2019 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: May 2019
Production reference: 1200519
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-83882-810-3
www.packtpub.com
Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Mapt is fully searchable
Copy and paste, print, and bookmark content
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.packt.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.packt.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.
Rahul Sharma is passionately curious about teaching programming. He has been writing software for the last two years. He got started with Rust with his work on Servo, a browser engine by Mozilla Research as part of his GSoC project. At present, he works at AtherEnergy, where he is building resilient cloud infrastructure for smart scooters. His interests include systems programming, distributed systems, compilers and type theory. He is also an occasional contributor to the Rust language and does mentoring of interns on the Servo project by Mozilla.
Vesa Kaihlavirta has been programming since he was five, beginning with C64 Basic. His main professional goal in life is to increase awareness of programming languages and software quality in all industries that use software. He's an Arch Linux Developer Fellow, and has been working in the telecom and financial industry for a decade. Vesa lives in Jyvaskyla, central Finland.
Claus Matzinger is a software engineer with a very diverse background. After working in a small company maintaining code for embedded devices, he joined a large corporation to work on legacy Smalltalk applications. This led to a great interest in programming languages early on, and Claus became the CTO for a health games start-up based on Scala technology. Since then, Claus' roles have shifted toward customer-facing roles in the IoT database technology start-up crate.io and, most recently, Microsoft. There, he hosts a podcast, writes code together with customers, and blogs about the solutions arising from these engagements. For more than 5 years, Claus has implemented software to help customers innovate, achieve, and maintain success.
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Title Page
Copyright
The Complete Rust Programming Reference Guide
About Packt
Why subscribe?
Packt.com
Contributors
About the authors
Packt is searching for authors like you
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Conventions used
Get in touch
Reviews
Getting Started with Rust
What is Rust and why should you care?
Installing the Rust compiler and toolchain
Using rustup.rs
A tour of the language
Primitive types
Declaring variables and immutability
Functions
Closures
Strings
Conditionals and decision making
Match expressions
Loops
User-defined types
Structs
Enums
Functions and methods on types
Impl blocks on structs
Impl blocks for enums
Modules, imports, and use statements
Collections
Arrays
Tuples
Vectors
Hashmaps
Slices
Iterators
Exercise – fixing the word counter
Summary
Managing Projects with Cargo
Package managers
Modules
Nested modules
File as a module
Directory as module
Cargo and crates
Creating a new Cargo project
Cargo and dependencies
Running tests with Cargo
Running examples with Cargo
Cargo workspace
Extending Cargo and tools
Subcommands and Cargo installation
cargo-watch
cargo-edit
cargo-deb
cargo-outdated
Linting code with clippy
Exploring the manifest file – Cargo.toml
Setting up a Rust development environment
Building a project with Cargo – imgtool
Summary
Tests, Documentation, and Benchmarks
Motivation for testing
Organizing tests
Testing primitives
Attributes
Assertion macros
Unit tests
First unit test
Running tests
Isolating test code
Failing tests
Ignoring tests
Integration tests
First integration test
Sharing common code
Documentation
Writing documentation
Generating and viewing documentation
Hosting documentation
Doc attributes
Documentation tests
Benchmarks
Built-in micro-benchmark harness
Benchmarking on stable Rust
Writing and testing a crate – logic gate simulator
Continuous integration with Travis CI
Summary
Types, Generics, and Traits
Type systems and why they matter
Generics
Creating generic types
Generic functions
Generic types
Generic implementations
Using generics
Abstracting behavior with traits
Traits
The many forms of traits
Marker traits
Simple traits
Generic traits
Associated type traits
Inherited traits
Using traits with generics – trait bounds
Trait bounds on types
Trait bounds on generic functions and impl blocks
Using + to compose traits as bounds
Trait bounds with impl trait syntax
Exploring standard library traits
True polymorphism using trait objects
Dispatch
Trait objects
Summary
Memory Management and Safety
Programs and memory
How do programs use memory?
Memory management and its kinds
Approaches to memory allocation
The stack
The heap
Memory management pitfalls
Memory safety
Trifecta of memory safety
Ownership
A brief on scopes
Move and copy semantics
Duplicating types via traits
Copy
Clone
Ownership in action
Borrowing
Borrowing rules
Borrowing in action
Method types based on borrowing
Lifetimes
Lifetime parameters
Lifetime elision and the rules
Lifetimes in user defined types
Lifetime in impl blocks
Multiple lifetimes
Lifetime subtyping
Specifying lifetime bounds on generic types
Pointer types in Rust
References – safe pointers
Raw pointers
Smart pointers
Drop
Deref and DerefMut
Types of smart pointers
Box<T>
Reference counted smart pointers
Rc<T>
Interior mutability
Cell<T>
RefCell<T>
Uses of interior mutability
Summary
Error Handling
Error handling prelude
Recoverable errors
Option
Result
Combinators on Option/Result
Common combinators
Using combinators
Converting between Option and Result
Early returns and the ? operator
Non-recoverable errors
User-friendly panics
Custom errors and the Error trait
Summary
Advanced Concepts
Type system tidbits
Blocks and expressions
Let statements
Loop as an expression
Type clarity and sign distinction in numeric types
Type inference
Type aliases
Strings
Owned strings – String
Borrowed strings – &str
Slicing and dicing strings
Using strings in functions
Joining strings
When to use &str versus String ?
Global values
Constants
Statics
Compile time functions – const fn
Dynamic statics using the lazy_static! macro
Iterators
Implementing a custom iterator
Advanced types
Unsized types
Function types
Never type ! and diverging functions
Unions
Cow
Advanced traits
Sized and ?Sized
Borrow and AsRef
ToOwned
From and Into
Trait objects and object safety
Universal function call syntax
Trait rules
Closures in depth
Fn closures
FnMut closures
FnOnce closures
Consts in structs, enums, and traits
Modules, paths, and imports
Imports
Re-exports
Selective privacy
Advanced match patterns and guards
Match guards
Advanced let destructure
Casting and coercion
Types and memory
Memory alignment
Exploring the std::mem module
Serialization and deserialization using serde
Summary
Concurrency
Program execution models
Concurrency
Approaches to concurrency
Kernel-based
User-level
Pitfalls
Concurrency in Rust
Thread basics
Customizing threads
Accessing data from threads
Concurrency models with threads
Shared state model
Shared ownership with Arc
Mutating shared data from threads
Mutex
Shared mutability with Arc and Mutex
RwLock
Communicating through message passing
Asynchronous channels
Synchronous channels
thread-safety in Rust
What is thread-safety?
Traits for thread-safety
Send
Sync
Concurrency using the actor model
Other crates
Summary
Metaprogramming with Macros
What is metaprogramming?
When to use and not use Rust macros
Macros in Rust and their types
Types of macros
Creating your first macro with macro_rules!
Built-in macros in the standard library
macro_rules! token types
Repetitions in macros
A more involved macro – writing a DSL for HashMap initialization
Macro use case – writing tests
Exercises
Procedural macros
Derive macros
Debugging macros
Useful procedural macro crates
Summary
Unsafe Rust and Foreign Function Interfaces
What is safe and unsafe really?
Unsafe functions and blocks
Unsafe traits and implementations
Calling C code from Rust
Calling Rust code from C
Using external C/C++ libraries from Rust
Creating native Python extensions with PyO3
Creating native extensions in Rust for Node.js
Summary
Logging
What is logging and why do we need it?
The need for logging frameworks
Logging frameworks and their key features
Approaches to logging
Unstructured logging
Structured logging
Logging in Rust
log – Rust's logging facade
The env_logger
log4rs
Structured logging using slog
Summary
Network Programming in Rust
Network programming prelude
Synchronous network I/O
Building a synchronous redis server
Asynchronous network I/O
Async abstractions in Rust
Mio
Futures
Tokio
Building an asynchronous redis server
Summary
Building Web Applications with Rust
Web applications in Rust
Typed HTTP with Hyper
Hyper server APIs – building a URL shortener 
hyper as a client – building a URL shortener client
Web frameworks
Actix-web basics
Building a bookmarks API using Actix-web
Summary
Lists, Lists, and More Lists
Linked lists
A transaction log
Adding entries
Log replay
After use
Wrap up
Upsides
Downsides
Doubly linked list
A better transaction log
Examining the log
Reverse
Wrap up
Upsides
Downsides
Skip lists
The best transaction log
The list
Adding data
Leveling up
Jumping around
Thoughts and discussion
Upsides
Downsides
Dynamic arrays
Favorite transactions
Internal arrays
Quick access
Wrap up
Upsides
Downsides
Summary
Further reading
Robust Trees
Binary search tree
IoT device management
More devices
Finding the right one
Finding all devices
Wrap up
Upsides
Downsides
Red-black tree
Better IoT device management
Even more devices
Balancing the tree
Finding the right one, now
Wrap up
Upsides
Downsides
Heaps
A huge inbox
Getting messages in
Taking messages out
Wrap up
Upsides
Downsides
Trie
More realistic IoT device management
Adding paths
Walking
Wrap up
Upsides
Downsides
B-Tree
An IoT database
Adding stuff
Searching for stuff
Walking the tree
Wrap up
Upsides
Downsides
Graphs
The literal Internet of Things
Neighborhood search
The shortest path
Wrap up
Upsides
Downsides
Summary
Exploring Maps and Sets
Hashing
Create your own
Message digestion
Wrap up
Maps
A location cache
The hash function
Adding locations
Fetching locations
Wrap up
Upsides
Downsides
Sets
Storing network addresses
Networked operations
Union
Intersection
Difference
Wrap up
Upsides
Downsides
Summary
Further reading
Collections in Rust
Sequences
Vec<T> and VecDeque<T>
Architecture
Insert
Look up
Remove
LinkedList<T>
Architecture
Insert
Look up
Remove
Wrap up
Maps and sets
HashMap and HashSet
Architecture
Insert
Lookup
Remove
BTreeMap and BTreeSet
Architecture
Insert
Look up
Remove
Wrap up
Summary
Further reading
Algorithm Evaluation
The Big O notation
Other people's code
The Big O
Asymptotic runtime complexity
Making your own
Loops
Recursion
Complexity classes
O(1)
O(log(n))
O(n)
O(n log(n))
O(n²)
O(2n)
Comparison
In the wild
Data structures
Everyday things
Exotic things
Summary
Further reading
Ordering Things
From chaos to order
Bubble sort
Shell sort
Heap sort
Merge sort
Quicksort
Summary
Further reading
Finding Stuff
Finding the best
Linear searches
Jump search
Binary searching
Wrap up
Summary
Further reading
Random and Combinatorial
Pseudo-random numbers
LCG
Wichmann-Hill
The rand crate
Back to front
Packing bags or the 0-1 knapsack problem
N queens
Advanced problem solving
Dynamic programming
The knapsack problem improved
Metaheuristic approaches
Example metaheuristic – genetic algorithms
Summary
Further reading
Algorithms of the Standard Library
Slicing and iteration
Iterator
Slices
Search
Linear search
Binary search
Sorting
Stable sorting
Unstable sorting
Summary
Further reading
Other Books You May Enjoy
Leave a review - let other readers know what you think
Rust is a powerful language with a rare combination of safety, speed, and zero-cost abstractions. This Learning Path is filled with clear and simple explanations of its features along with real-world examples, demonstrating how you can build robust, scalable, and reliable programs.
You'll get started with an introduction to Rust data structures, algorithms, and essential language constructs. Next, you will understand how to store data using linked lists, arrays, stacks, and queues. You'll also learn to implement sorting and searching algorithms, such as Brute Force algorithms, Greedy algorithms, Dynamic Programming, and Backtracking. As you progress, you'll pick up on using Rust for systems programming, network programming, and the web. You'll then move on to discover a variety of techniques, right from writing memory-safe code, to building idiomatic Rust libraries, and even advanced macros.
By the end of this Learning Path, you'll be able to implement Rust for enterprise projects, writing better tests and documentation, designing for performance, and creating idiomatic Rust code.
This Learning Path includes content from the following Packt products:
Mastering Rust - Second Edition by Rahul Sharma and Vesa Kaihlavirta
Hands-On Data Structures and Algorithms with Rust by Claus Matzinger
If you are already familiar with an imperative language and now want to progress from being a beginner to an intermediate-level Rust programmer, this Learning Path is for you. Developers who are already familiar with Rust and want to delve deeper into the essential data structures and algorithms in Rust will also find this Learning Path useful.
Chapter 1, Getting Started with Rust, gives a brief history on Rust and the motivation behind its design, and covers basic language syntax. The chapter ends with an exercise covering all the language features.
Chapter 2, Managing Projects with Cargo, shows how Rust organizes large projects with its dedicated package manager. This serves as the basis for further chapters. It also covers editor integration with the Visual Studio Code editor.
Chapter 3, Tests, Documentation, and Benchmarks, explores the built-in testing harness, writing unit tests, integration tests, and how to write documentation in Rust. We also cover the benchmarking facilities of Rust code. Later, as a final exercise, we build a complete crate with documentation and tests.
Chapter 4, Types, Generics, and Traits, explores Rust's expressive type system and goes on to explain various ways of using the type system by building a complex number library.
Chapter 5, Memory Management and Safety, starts with the motivation for memory management and the various pitfalls in conventional low-level programming languages related to memory. It then moves toward explaining Rust's unique compile-time memory management ideas. We also explain various smart pointer types in Rust.
Chapter 6, Error Handling, starts with the motivation for error handling and explores different models of error handling in other languages. The chapter then examine Rust's error-handling strategy and types, before exploring handling errors in non-recoverable situations. The chapter ends with a library implementing custom error types.
Chapter 7, Advanced Concepts, explores some of the concepts already introduced in previous chapters, in more detail. It provides details on the underlying model of some of the type system abstractions provided by Rust.
Chapter 8, Concurrency, explores Rust's concurrency models and APIs in the standard libraries and teaches you how to build highly concurrent programs with no data races.
Chapter 9, Metaprogramming with Macros, examines how you can write code to generate code using the powerful and advanced macro construct of Rust, and outlines the language's declarative and procedural macros by building both types of macros.
Chapter 10, Unsafe Rust and Foreign Function Interfaces, explores the unsafe mode of Rust and the APIs on offer for interoperating Rust with other languages. The examples includes both calling into Rust from other languages, such as Python, Node.js, and C, as well as covering how Rust can be called from other languages.
Chapter 11, Logging, explains why logging is an important practice in software development, answering why we need logging frameworks, and exploring the crates on offer in the Rust ecosystem that can be used to help integrate logging into the application.
Chapter 12, Network Programming in Rust Sync, gives a brief introduction to network programming. After going through the basics, the chapter covers building a Redis server that can talk to the official Redis client. Lastly, the chapter explains how to use the standard library networking primitives and the Tokio and futures crates.
Chapter 13, Building Web Applications with Rust, starts by exploring the HTTP protocol and builds a simple URL shortener server using the hyper crate, followed by building a URL shortener client using the reqwest crate. In the end, we explore actix-web, a highperformance Async web application framework to build a bookmarks API server.
Chapter 14, Lists, Lists, and More Lists, covers the first data structures: lists. Using several examples, this chapter goes into variations of sequential data structures and their implementations.
Chapter 15, Robust Trees, continues our journey through popular data structures: trees are next on the list. In several detailed examples, we explore the inner workings of these efficient designs and how they improve application performance considerably.
Chapter 16, Exploring Maps and Sets, explores the most popular key-value stores: maps. In this chapter, techniques surrounding hash maps; hashing; and their close relative, the set; are described in detail.
Chapter 17, Collections in Rust, attempts to connect to the Rust programmer's daily life, going into the details of the Rust std::collections library, which contains the various data structures provided by the Rust standard library.
Chapter 18, Algorithm Evaluation, teaches you how to evaluate and compare algorithms.
Chapter 19, Ordering Things, will look at sorting values, an important task in programming—this chapter uncovers how that can be done quickly and safely.
Chapter 20, Finding Stuff, moves onto searching, which is especially important if there is no fundamental data structure to support it. In these cases, we use algorithms to be able to quickly find what we are looking for.
Chapter 21, Random and Combinatorial, is where we will see that, outside of sorting and searching, there are many problems that can be tackled algorithmically. This chapter is all about those: random number generation, backtracking, and improving computational complexities.
Chapter 22, Algorithms of the Standard Library, explores how the Rust standard library does things when it comes to everyday algorithmic tasks such as sorting and searching.
To really grasp the content of this book, it is recommended that you write out the example code and try fiddling with code to get familiar with the Rust's error messages, so they can guide you toward writing correct programs. You can either use Linux or Windows OS.
Here are a few recommendations for text editors and other tools:
Microsoft's Visual Studio Code (
https://code.visualstudio.com/
), arguably one of the best Rust code editors
Rust support for Visual Studio Code via a plugin (
https://github.com/rust-lang/rls-vscode
)
Rust Language Server (RLS), found at
https://github.com/rust-lang/rls-vscode
, installed via rustup (
https://rustup.rs/
)
Debugging support using the LLDB frontend plugin (
https://github.com/vadimcn/vscode-lldb
) for Visual Studio Code.
You can download the example code files for this book from your account at www.packt.com. If you purchased this book elsewhere, you can visit www.packt.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at
www.packt.com
.
Select the
SUPPORT
tab.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box and follow the onscreen instructions.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR/7-Zip for Windows
Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/The-Complete-Rust-Programming-Reference-Guide. In case there's an update to the code, it will be updated on the existing GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
There are a number of text conventions used throughout this book.
CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "However, it makes the whole thing safe—thanks toRefCells checking borrowing rules at runtime."
A block of code is set as follows:
struct Node {value: i32,next: Option<Node>}
Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "Select System info from the Administration panel"
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packt.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packt.com.
Learning a new language is like building a house – the foundation needs to be strong. With a language that changes the way you think and reason about your code, there's always more effort involved in the beginning, and it's important to be aware of that. The end result, however, is that you get to shift your thinking with these new-found concepts and tools.
This chapter will give you a whirlwind tour on the design philosophy of Rust, an overview of its syntax and the type system. We assume that you have a basic knowledge of mainstream languages such as C, C++, or Python, and the ideas that surround object-oriented programming. Each section will contain example code, along with an explanation of it. There will be ample code examples and output from the compiler, that will help you become familiar with the language. We'll also delve into a brief history of the language and how it continues to evolve.
Getting familiar with a new language requires perseverance, patience, and practice. I highly recommend to all readers that you manually write and don't copy/paste the code examples listed here. The best part of writing and fiddling with Rust code is the precise and helpful error messages you get from the compiler, which the Rust community often likes to call error-driven development. We'll see these errors frequently throughout this book to understand how the compiler thinks of our code.
In this chapter, we will cover the following topics:
What is Rust and why should you care?
Installing the Rust compiler and the toolchain
A brief tour of the language and its syntax
A final exercise, where we'll put what we've learned together
The Rust toolchain has two major components: the compiler, rustc, and the package manager, cargo, which helps manage Rust projects. The toolchain comes in three release channels:
Nightly
: The daily successful build from the master development branch. This contains all the latest features, many of which are unstable.
Beta
: This is released every six weeks. A new beta branch is taken from nightly. It contains only features that are flagged as stable.
Stable
: This is released every six weeks. The previous beta branch becomes the new stable release.
Developers are encouraged to use the stable release channel. However, the nightly version enables bleeding edge features, and some libraries and programs require it. You can change to the nightly toolchain easily with rustup. We'll see how we can do that in a moment.
Rustup is a tool to that installs the Rust compiler on all supported platforms. To make it easier for developers on different platforms to download and use the language, the Rust team developed rustup. It's a command-line tool written in Rust that provides an easy way to install pre-built binaries of the compiler and binary builds of the standard library for cross compiling needs. It can also install other components, such as the Rust source code, documentation, Rust formatting tool (rustfmt), Rust Language Server (RLS for IDEs), and other developer tools, and it runs on all platforms, including Windows.
From their official page at https://rustup.rs, the recommended way to install the toolchain is to run the following command:
curl https://sh.rustup.rs -sSf | sh
By default, the installer installs the stable version of the Rust compiler, its package manager, Cargo, and the language's standard library documentation so that it can be viewed offline. These are installed by default under the ~/.cargo directory. Rustup also updates your PATH environment variable to point to this directory.
The following is a screenshot of running the preceding command on Ubuntu 16.04:
If you need to make any changes to your installation, choose 2. However, the defaults are fine for us, so we'll go ahead and choose 1. Here's the output after the installation:
Rustup also has other capabilities, such as updating the toolchain to the latest version, which can be done by running rustup update. It can also update itself via rustup self update. It also provides directory-specific toolchain configuration. The default toolchain is set globally to whatever toolchain gets installed, which in most cases is the stable toolchain. You can view the default one by invoking rustup show. If you want to use the latest nightly toolchain for one of your projects, you can tell rustup to switch to nightly for that particular directory by running rustup override set nightly. If, for some reason, someone wants to use an older version of the toolchain or downgrade (say, the nightly build on 2016-06-03), rustup can also download that if we were to run rustup install nightly-2016-06-03, followed by setting the same using the override sub-command. More information on rustup can be found at https://github.com/rust-lang-nursery/rustup.rs.
Now, you should have everything you need to compile and run programs written in Rust. Let's get Rusty!
Rust has the following built-in primitive types:
bool
: These are the usual booleans and can be either
true
or
false
.
char
: Characters, such as
e
.
Integer types: These are characterized by the bit width. Rust supports integers that are up to 128 bits wide:
signed
unsigned
i8
u8
i16
u16
i32
u32
i64
u64
i128
u128
isize
: The pointer-sized signed integer type. Equivalent to
i32
on 32-bit CPU and
i64
on 64-bit CPU.
usize
: The pointer-sized unsigned integer type. Equivalent to
i32
on 32-bit CPU and
i64
on 64-bit CPU.
f32
: The 32-bit floating point type. Implements the IEEE 754 standard for floating point representation.
f64
: The 64-bit floating point type.
[T; N]
: A fixed-size array, for the element type,
T
, and the non-negative compile-time constant size N.
[T]
: A dynamically-sized view into a contiguous sequence, for any type
T
.
str
: String slices, mainly used as a reference, that is,
&str
.
(T, U, ..)
: A finite sequence, (T, U, ..) where T and U can be different types.
fn(i32) -> i32
: A function that takes an
i32
and returns an
i32
. Functions also have a type.