Introduction to Rust and its Ecosystem
local graph
Chapter 2 — Introduction to Rust and its Ecosystem
Section titled “Chapter 2 — Introduction to Rust and its Ecosystem”The Rust programming language is sponsored by Mozilla and supported by a community of developers from across the globe. Rust is promoted as a systems programming language that supports automatic memory management without the overhead of a runtime or a garbage collector, concurrency without data races enforced by the compiler, and zero cost abstractions and generics. In subsequent sections, we will discuss these features in more detail. Rust is statically typed and borrows a number of functional programming ideas. A fascinating aspect of Rust is the use of the type system to guarantee memory safety without using a runtime. This makes Rust uniquely suitable for low-resource embedded devices and real-time systems, which require strong guarantees around code correctness. On the flip side, this often means that the compiler has to do a lot more work to ensure syntactical correctness and then translate source code, resulting in higher build times. While the community is working on methods to reduce compile time as much as possible, this is still an important issue encountered by a lot of developers.
The Low Level Virtual Machine (LLVM) project started as a university research project aimed at developing a set of tools for building compilers that can generate machine code for a range of CPU architectures. This was achieved using the LLVM intermediate representation (LLVM IR). The toolchain can compile any higher-level language to LLVM IR, which can then be targeted for a given CPU. The Rust compiler depends heavily on the LLVM project for interoperability, using it as a backend. It actually translates Rust code into LLVM’s intermediate representation and optimizes it as necessary. LLVM then translates that into machine code for the specific platform, which gets run on the CPU.
In this chapter, we will cover the following topics:
- An introduction to the ecosystem and how Rust works
- Installing Rust and setting up the toolchain
- An introduction to its major features, starting from the borrow checker and how ownership works
- Generics and how the trait system works with the ownership model
- Error handling and the macro system
- Concurrency primitives
- Testing primitives
Note that this chapter is a very high-level overview of the language and some of its most distinctive features, not a deep dive.
The success or failure of an open source project is often determined by the strength of the community around it. Having a coherent ecosystem helps in building a strong community. Since Rust is primarily driven by Mozilla, they have been able to build a strong ecosystem around it, the primary components being:
- Source code: Rust hosts all the source code in GitHub. Developers are encouraged to report bugs and submit pull requests in there. At the time of writing, the Rust repository on GitHub has 1,868 unique contributors, over 2,700 open bug reports, and 90 open pull requests. The core Rust team is composed of Mozilla employees and contributors from other organizations (like Google, Baidu, and so on). The team uses GitHub for all collaborations; even major changes to any component have to be first proposed by writing a Request For Comments (RFC). This way, everyone has a chance to take a look at it and collaborate on improving it. Once it is approved, the actual change can be implemented.
- Compiler: The Rust compiler is named rustc. Since Rust follows semantic versioning for compiler releases, there cannot be any backward incompatible breaking changes between minor releases. At the time of writing this book, the compiler has already reached version 1.0, thus it can be assumed that there will not be any breaking changes till version 2.0. Note that breaking changes do slip once in a while. But in all those cases, they are treated as bugs and fixed as soon as possible.
To facilitate adding new compiler features without breaking existing dependent libraries, Rust releases new compiler versions in stages. At any point, three different versions of the compiler (and the standard library) are maintained.
- The first one is called nightly. As the name implies, it is built each night from the tip of the source tree. Since this is only tested by unit and integration tests, this release often has more bugs in the real world.
- The second stage is beta, which is a planned release. By the time a nightly has reached this stage, it has gone through multiple rounds of unit, integration, and regression testing. Additionally, the community has had the time to use it in real projects and share feedback with the Rust team.
- Once everyone is confident about the release, it is tagged as a stable release and pushed out. Since the compiler supports a variety of platforms (from Windows to Redox) and architectures (amd64), each release has pre-built binaries for all combinations of platforms and architectures.
- Installation mechanism: The community supported installation mechanism is via a tool called rustup. This tool can install a given version of Rust along with everything needed to use it (including the compiler, standard library, package manager, and so on).
- Package manager: Rust’s package manager is called Cargo, while individual packages are called crates. All external libraries and applications can be packaged in a crate and published using the Cargo CLI tool. A user can then use it to search for and install packages. All crates can be searched using the following website: https://crates.io/. For all packages hosted on crates.io, the corresponding documentation is available at: https://docs.rs/.
The Rust toolchain installer is available at: https://www.rustup.rs/. The following commands will install all three versions of the toolchain on a system. For the examples in this book, we will use a Linux machine running Ubuntu 16.04. While most of Rust should not depend on the OS, there can be minor differences.
We will point out any strict dependencies on the OS:
# source $HOME/.cargo/env# rustup install nightly betaWe will need to put Cargo’s bin directory to our PATH by editing .bashrc. Run the following to do that:
$ echo "export PATH=$HOME/.cargo/bin:$PATH" >> ~/.bashrcA Rust installation comes with a lot of documentation built in; they can be accessed by running the following command. This should open up the documentation in a browser window:
# rustup docThe next step is to set up a Rust project and run it, all using Cargo:
# cargo new --bin hello-rustThis tells Cargo to set up a new project called hello-rust in the current directory. Cargo will create a directory of that name and set up the basic structure. Since the type of this project is set to be a binary, Cargo will generate a file called main.rs which will have an empty main function, the entry point for the application. The other (default) option here is that of a library, in this case, a file named lib.rs will be generated. The file named Cargo.toml has a bunch of metadata for the current project and is used by Cargo. All source code is located in the src directory:
# tree hello-rust/hello-rust/├── Cargo.toml└── src └── main.rs
1 directory, 2 filesThe project can then be built and run using the following command. Note that this command should be run from the hello-rust directory that Cargo created previously:
# cargo runInterestingly, this command modifies the directory quite a bit. The target directory contains compilation artifacts. The structure of this is heavily platform dependent, but always includes everything necessary to run the application in the given build mode. The default build mode is debug, which includes debugging information and symbols to be used with a debugger:
# tree hello-rust/hello-rust/├── Cargo.lock├── Cargo.toml├── src│ └── main.rs└── target └── debug ├── build ├── deps │ └── hello_rust-392ba379262c5523 ├── examples ├── hello-rust ├── hello-rust.d ├── incremental └── native
8 directories, 6 filesA packaged Rust application is called a crate. Rust crates are published to crates.io. Once published, anyone can use the web interface or the cargo CLI to search for crates, as shown in the following code snippet. This operation needs a working internet connection so that cargo can communicate with crates.io:
# cargo search term Updating registry \`https://github.com/rust-lang/crates.io-index\`term = "0.4.6" # A terminal formatting libraryansi_term = "0.9.0" # Library for ANSI terminal colours and styles (bold, underline)term-painter = "0.2.4" # Coloring and formatting terminal outputterm_size = "0.3.0" # functions for determining terminal sizes and dimensionsrust_erl_ext = "0.2.1" # Erlang external term format codec.slog-term = "2.2.0" # Unix terminal drain and formatter for slog-rscolored = "1.5.2" # The most simple way to add colors in your terminalterm_grid = "0.1.6" # Library for formatting strings into a grid layoutrust-tfidf = "1.0.4" # Library to calculate TF-IDF (Term Frequency - Inverse Document Frequency) for generic documentsaterm = "0.20.0" # Implementation of the Annotated Terms data structure... and 1147 crates more (use --limit N to see more)Now, say we want to use the term crate in our application; we will need to edit the Cargo.toml file and include it in the [dependencies] section, as shown in the following code snippet. This particular crate helps in formatting terminal colors. Using this crate, we would like to print the words hello and world in green and red, respectively:
[package]name = "hello-rust"version = "0.1.0"authors = ["Foo Bar <[email protected]>"]
[dependencies]term = "0.4.6"To actually use the crate in our application, we need to modify the main.rs file, as shown in the following code snippet. We will discuss the language in detail in subsequent sections, but here is a small overview. The following sample is a simple program that prints the string hello world! on the screen. Further, it prints hello in green and world! in red:
extern crate term;
fn main() { let mut t = term::stdout().unwrap(); t.fg(term::color::GREEN).unwrap(); write!(t, "hello, ").unwrap();
t.fg(term::color::RED).unwrap(); writeln!(t, "world!").unwrap();
t.reset().unwrap();}In Rust, each application must have a single entry point called main, which should be defined as a function that does not take in parameters. Functions are defined using the fn keyword. The phrase extern crate term tells the toolchain that we want to use an external crate as a dependency of our current application.
Now, we can run it using Cargo. It automatically downloads and builds the library we need and all of its dependencies. Finally, it calls the Rust compiler so that our application is linked with the library and runs the executable. Cargo also generates a file called Cargo.lock that has a snapshot of everything needed to run the application in a consistent manner. This file should never be edited manually. Since cargo caches all dependencies locally, subsequent invocations do not need internet access:
$ cargo run Updating registry \`https://github.com/rust-lang/crates.io-index\` Compiling term v0.4.6 Compiling hello-rust v0.1.0 (file:///Users/Abhishek/Desktop/rust-book/src/chapter2/hello-rust) Finished dev [unoptimized + debuginfo] target(s) in 3.20 secs Running \`target/debug/hello-rust\`hello, world!The most important aspect of Rust is the ownership and borrowing model. Based on the strict enforcing of borrowing rules, the compiler can guarantee memory safety without an external garbage collector. This is done by the borrow checker, a subsystem of the compiler. By definition, every resource created has a lifetime and an owner associated with it, which operates under the following rules:
- Each resource has exactly one owner at any point in time. By default, the owner is the variable that created that resource, and its lifetime is the lifetime of the enclosing scope. Others can borrow or copy the resource if they need to. Note that a resource can be anything from a variable or a function. A function takes ownership of a resource from its caller; returning from the function transfers back ownership.
- When the owner’s scope has finished executing, all resources owned by it will be dropped. This is statically computed by the compiler, which then produces machine code accordingly.
Some examples of these rules are shown in the following code snippet:
fn main() { let s = String::from("Test"); heap_example(s);}
fn heap_example(input: String) { let mystr = input; let _otherstr = mystr; println!("{}", mystr);}In Rust, variables are declared using the let keyword. All variables are immutable by default and can be made mutable by using the mut keyword. The :: syntax refers to an object in the given namespace, in this case, the from function. println! is a built-in macro that the compiler provides; it is used to write to the standard output with a trailing newline. Functions are defined using the fn keyword. When we try to build it, we get the following error:
# rustc ownership-heap.rserror[E0382]: use of moved value: \`mystr\` --> ownership-heap.rs:9:20 |8 | let _otherstr = mystr; | --------- value moved here9 | println!("{}", mystr); | ^^^^^ value used here after move | = note: move occurs because \`mystr\` has type \`std::string::String\`, which does not implement the \`Copy\` trait
error: aborting due to previous errorIn this example, a string resource is created which is owned by the variable mystr, in the function heap_example. Thus, its lifetime is the same as its scope. Under the hood, since the compiler does not know the length of the string at compile time, it must place it on the heap. The owner variable is created on the stack and points to the resource on the heap. When we assign that resource to a new variable, the resource is now owned by the new variable. Rust will mark mystr as invalid at this point to prevent situations where the memory associated with the resource might be freed multiple times. Thus, compilation fails here to guarantee memory safety. We can force the compiler to copy the resource and have the second owner point to the newly created resource. For that, we will need to .clone() the resource named mystr. Here is how it looks:
fn main() { let s = String::from("Test"); heap_example(s);}
fn heap_example(input: String) { let mystr = input; let _otherstr = mystr.clone(); println!("{}", mystr);}As expected, this does not throw any errors on compilation and prints the given string “Test” on running. Notice that till now, we have been using Cargo for running our code. Since in this case, we just have a simple file and no external dependency, we will use the Rust compiler directly to compile our code, and we will run it manually:
$ rustc ownership-heap-fixed.rs && ./ownership-heap-fixedTestConsider the code sample below which shows the case when resources are stored on the stack:
fn main() { let i = 42; stack_example(i);}
fn stack_example(input: i32) { let x = input; let _y = x; println!("{}", x);}Interestingly, though it looks exactly the same as the code block before, this does not throw a compilation error. We build and run this using the Rust compiler directly from the command line:
# rustc ownership-stack.rs && ./ownership-stack42The difference is in the types of the variables. Here, the original owner and the resource are both created on the stack. When the resource is reassigned, it is copied over to the new owner. This is possible only because the compiler knows that the size of an integer is always fixed (and hence can be placed on the stack). Rust provides a special way to say that a type can be placed on the stack via the Copy trait. Our example works only because built-in integers (and some other types) are marked with this trait. We will explain the trait system in more detail in subsequent sections.
One might have noticed that copying a resource of unknown length to a function might lead to memory bloats. In a lot of languages, the caller will pass a pointer to a memory location, and then to the function. Rust does this by using references. These allow you to refer to a resource without actually owning it. When a function receives a reference to a resource, we say that it borrowed that resource. In the following example, the function heap_example borrows the resource owned by the variable s. Since borrowing is not absolute ownership, the scope of the borrowing variable does not affect how memory associated with the resource is freed. That also means there is no chance of freeing the borrowed resource multiple times in the function, since nobody in the function’s scope actually owns that resource. Thus, the earlier code that failed works in this case:
fn main() { let s = String::from("Test"); heap_example(&s);}
fn heap_example(input: &String) { let mystr = input; let _otherstr = mystr; println!("{}", mystr);}The borrowing rules also imply that the borrow is immutable. However, there can be cases where one needs to mutate the borrow. To handle those cases, Rust allows mutable references (or borrowing). As one would expect, this takes us back to the problem we had in the first example, and compilation fails with the following code:
fn main() { let mut s = String::from("Test"); heap_example(&mut s);}
fn heap_example(input: &mut String) { let mystr = input; let _otherstr = mystr; println!("{}", mystr);}Note that a resource can be mutably borrowed only once in a scope. The compiler will refuse to compile code that tries to do otherwise. While this might look like an annoying error, you need to remember that in a working application, these functions will often be called from competing threads. If there is a synchronization error due to a programming fault, we will end up with a data race where multiple unsynchronized threads race to modify the same resource. This feature helps prevent such situations.
Another language feature that is closely related to references is that of a lifetime. A reference lives as long as it is in scope, thus its lifetime is that of the enclosing scope. All variables declared in Rust can have a lifetime explicit elision that puts a name to its lifetime. This is useful for the borrow checker to reason about the relative lifetimes of variables. In general, one does not need to put an explicit lifetime name to each and every variable since the compiler manages that. In certain scenarios, this is needed, especially when automatic lifetime determination cannot work. Let’s look at an example where this happens:
fn main() { let v1 = vec![1, 2, 3, 4, 5]; let v2 = vec![1, 2];
println!("{:?}", longer_vector(&v1, &v2));}
fn longer_vector(x: &[i32], y: &[i32]) -> &[i32] { if x.len() > y.len() { x } else { y }}The vec! macro constructs a vector from the given list of objects. Note that unlike previous examples, our function here needs to return a value back to the caller. We need to specify the return type using the arrow syntax. Here, we are given two vectors, and we want to print the longest of the two. Our longer_vector function does just that. It takes in references to two vectors, computes their length, and returns a reference to the one with the larger length. This fails to compile with the following error:
# rustc lifetime.rserror[E0106]: missing lifetime specifier --> lifetime.rs:8:43 |8 | fn longer_vector(x: &[i32], y: &[i32]) -> &[i32] { | ^ expected lifetime parameter | = help: this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from \`x\` or \`y\`
error: aborting due to previous errorThis tells us that the compiler could not determine if the returned reference should refer to the first parameter or the second, so it could not determine how long it should live. There is no way this can be determined at compile time since we have no control of the inputs. A key insight here is that we do not need to know the lifetimes of all the references at compile time. We need to make sure the following things hold true:
- The two inputs should have the same lifetimes since we want to compare their lengths in the function
- The return value should have the same lifetime as that of the input, which is the longer of the two
Given these two axioms, it follows that the two inputs and the return should have the same lifetime. We can annotate this, as shown in the following code snippet:
fn longer_vector<'a>(x: &'a[i32], y: &'a[i32]) -> &'a[i32] { if x.len() > y.len() { x } else { y }}This works as expected since the compiler can happily guarantee code correctness. Lifetime parameters can also be attached to structs and method definitions. There is a special lifetime called ‘static that refers to the entire duration of the program.
Rust recently accepted a proposal to add a new designated lifetime called ‘fn that will be equal to the scope of the innermost function or closure.
Rust supports writing generic code that is later bound with more concrete types, either during compile time or during runtime. People who are familiar with templates in C++ might notice that generics in Rust are pretty similar to templates, as far as syntax goes. The following example illustrates how to use generic programming. We also introduce some new constructs which we haven’t discussed before, which we will explain as we proceed.
Much like C and C++, a Rust struct defines a user-defined type that aggregates multiple logically connected resources in one unit. Our struct here defines a tuple of two variables. We define a generic struct and we use a generic type parameter, written here as <T>. Each member of the struct is defined to be of that type. We later define a generic function that sums the two elements of the tuple. Let’s look at a naive implementation of this:
struct Tuple<T> { first: T, second: T,}
fn main() { let tuple_u32: Tuple<u32> = Tuple {first: 4u32, second: 2u32 }; let tuple_u64: Tuple<u64> = Tuple {first: 5u64, second: 6u64 }; println!("{}", sum(tuple_u32)); println!("{}", sum(tuple_u64));
let tuple: Tuple<String> = Tuple {first: "One".to_owned(), second: "Two".to_owned() }; println!("{}", sum(tuple));}
fn sum<T>(tuple: Tuple<T>) -> T{ tuple.first + tuple.second}This fails to compile, and the compiler throws the following error:
$ rustc generic-function.rserror[E0369]: binary operation \`+\` cannot be applied to type \`T\` --> generic-function-error.rs:18:5 |18 | tuple.first + tuple.second | ^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: \`T\` might need a bound for \`std::ops::Add\`
error: aborting due to previous errorThis error is important. The compiler is telling us that it does not know how to add two operands of type T. It also (correctly) guessed that the T type needs to be bound by the Add trait. This means that the list of possible concrete types for T should only have types that implement the Add trait, which are types whose concrete references can be added. Let’s go ahead and put the trait bound in the sum function. Our code should look like this now:
use std::ops::Add;
struct Tuple<T> { first: T, second: T,}
fn main() { let tuple_u32: Tuple<u32> = Tuple {first: 4u32, second: 2u32 }; let tuple_u64: Tuple<u64> = Tuple {first: 5u64, second: 6u64 }; println!("{}", sum(tuple_u32)); println!("{}", sum(tuple_u64));
// These lines fail to compile let tuple: Tuple<String> = Tuple {first: "One".to_owned(), second: "Two".to_owned() }; println!("{}", sum(tuple));}
// We constrain the possible types of T to those which implement the Add traitfn sum<T: Add<Output = T>>(tuple: Tuple<T>) -> T{ tuple.first + tuple.second}For this to work, the elements must be summable; there should be a logical meaning of summing them. So, we have constrained the possible types the T parameter can have to those which have the Add trait implemented. We also need to let the compiler know that the output for this function should be of the type T. Given this information, we can construct our tuples and call the sum function on them, and they will behave as expected. Also, note that a tuple of strings will fail to compile with the error, since the Add trait is not implemented for strings.
From the last example, one might notice that traits are essential to properly implement generics. They help the compiler reason about properties of generic types. In essence, a trait defines properties of a type. The library defines a bunch of commonly used traits and their implementations for built-in types. For any user-defined types, it’s up to the user to define what properties those types should have by defining and implementing traits.
trait Max<T> { fn max(&self) -> T;}
struct ThreeTuple<T> { first: T, second: T, third: T,}
// PartialOrd enables comparingimpl<T: PartialOrd + Copy> Max<T> for ThreeTuple<T> { fn max(&self) -> T { if self.first >= self.second && self.first >= self.third { self.first } else if self.second >= self.first && self.second >= self.third { self.second } else { self.third } }}
struct TwoTuple<T> { first: T, second: T,}
impl<T: PartialOrd + Copy> Max<T> for TwoTuple<T> { fn max(&self) -> T { if self.first >= self.second { self.first } else { self.second } }}
fn main() { let two_tuple: TwoTuple<u32> = TwoTuple {first: 4u32, second: 2u32 }; let three_tuple: ThreeTuple<u64> = ThreeTuple {first: 6u64, second: 5u64, third: 10u64 };
println!("{}", two_tuple.max()); println!("{}", three_tuple.max());}We start by defining a generic trait of type T. Our trait has a single function that will return the maximum of the given type that implements it. What counts as the maximum is an implementation detail and is not important at this stage. We then define a tuple of three elements, each of the same generic type. Later, we implement our trait for that type we defined. In Rust, a function returns the last expression if there is no explicit return statement. Using this style is considered idiomatic in the community. Our max function uses this feature in the if…else block. For the implementation to work, the generic types must have an ordering relation defined between them so that we can compare them. In Rust, this is achieved by constraining the possible types to those which implement the PartialOrd trait. We also need to put a constraint on the Copy trait so that the compiler can make copies of the self parameter before returning from the function. We move on to defining another tuple, which has two elements. We implement the same trait here in a similar fashion. When we actually use these in our main function, they work as expected.
Traits can also be used to extend built-in types and add new functionalities. Let’s look at the following example:
// Trait for our behaviortrait Sawtooth { fn sawtooth(&self) -> Self;}
// Extending the builtin f64 typeimpl Sawtooth for f64 { fn sawtooth(&self) -> f64 { self - self.floor() }}
fn main() { println!("{}", 2.34f64.sawtooth());}Here, we want to implement the sawtooth (https://en.wikipedia.org/wiki/Sawtooth_wave) function on the built-in f64 type. This function is not available in the standard library, so we would need to write some code to get it working by extending the standard library. To have this seamlessly integrated into the type system, we will need to define a trait and implement it for the f64 type. This enables us to use the new function using the dot notation like any other built-in function on the f64 type.
The standard library provides a number of built-in traits; the most common of these are Display and Debug. These two are used to format types while printing. Display corresponds to the empty formatter {} and Debug corresponds to format debugging output. All of the mathematical operations are defined as traits, such as Add, Div, and so on. The compiler attempts to provide default implementations for user-defined types if they are marked with the #[derive] attribute. However, an implementation might choose to override any of these if necessary. An example of this is shown in the following code snippet:
use std::fmt;use std::fmt::Display;
#[derive(Debug, Hash)]struct Point<T> { x: T, y: T,}
impl<T> fmt::Display for Point<T> where T: Display { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "({}, {})", self.x, self.y) }}
fn main() { let p: Point<u32> = Point { x: 4u32, y: 2u32 };
// uses Display println!("{}", p);
// uses Debug println!("{:?}", p);}We define a generic point structure with two fields. We let the compiler generate implementations of some common traits. We must, however, implement the Display trait by hand, since the compiler cannot determine the best way to display user-defined types. We have to constrain the generic type to types that implement Display using the where clause. This example also demonstrates the alternate way to constrain types based on traits. Having set all of this up, we can display our point using the default formatter. This produces the following output:
# rustc derive.rs && ./derive(4, 2)Point { x: 4, y: 2 }One of Rust’s major goals is enabling the developer to write robust software. An essential component of this is advanced error handling. In this section, we will take a deeper look at how Rust does error handling. But before that, let’s take a detour and look at some type theory. Specifically, we are interested in algebraic data types (ADT), types formed by combining other types. The two most common ADTs are sum and product types. A struct in Rust is an example of a product type. This name derives from the fact that given a struct, the range of its type is essentially the Cartesian product of the ranges of each of its components, since an instance of the type has values for all of its constituent types. In contrast, a sum type is when the ADT can assume the type of only one of its constituents. An example of this is an enum in Rust. While similar to enums in C and other languages, Rust enums provide a number of enhancements: they allow variants to carry data.
Now, back to error handling. Rust mandates that operations which can result in an error must return a special enum that carries the result. Conveniently, this enum looks like this:
enum Result<T, E> { Ok(T), Err(E),}The two possible options are called variants. In this case, they represent the non-error case and the error case, respectively. Note that this is generically defined so that an implementation is free to define the types in both cases. This is useful in applications that want to expand on the standard error type and implement custom errors. Let’s look at an example of this in action:
use std::fmt;use std::error::Error;
#[derive(Debug)]enum OperationsError { DivideByZeroError,}
// Useful for displaying the error nicelyimpl fmt::Display for OperationsError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { OperationsError::DivideByZeroError => f.write_str("Cannot divide by zero"), } }}
// Registers the custom error as an errorimpl Error for OperationsError { fn description(&self) -> &str { match *self { OperationsError::DivideByZeroError => "Cannot divide by zero", } }}
// Divides the dividend by the divisor and returns the result. Returns// an error if the divisor is zerofn divide(dividend: u32, divisor: u32) -> Result<u32, OperationsError> { if divisor == 0u32 { Err(OperationsError::DivideByZeroError) } else { Ok(dividend / divisor) }}
fn main() { let result1 = divide(100, 0); println!("{:?}", result1);
let result2 = divide(100, 2); println!("{:?}", result2.unwrap());}For this example, we define a function that simply returns the quotient when the first operand is divided by the second. This function must handle the error case when the divisor is zero. We also want it to signal an error to its caller if that is the case. Also, let’s assume that this is a part of a library that will expand to include more such operations. To make the code manageable, we create an error class for our library, with one element that represents the divide by zero error. For the Rust compiler to know that the enum is an error type, our enum has to implement the Error trait from the standard library. It also needs to implement the Display trait manually. Having set up this boilerplate, we can define our division method. We will take advantage of the generic Result trait to annotate that on success, it should return a u32, the same type as the operands. On failure, it should return an error of type OperationsError. In the function, we raise the error if our divisor is zero. Otherwise, we carry out the division, wrap the result in a Ok so that it becomes a variant of the Result enum, and return it. In our main function, we call this with a zero divisor. The result will be an error, as shown by the first print macro. In the second invocation, we know that the divisor is not zero. Thus, we can safely unwrap the result to convert it from Ok(50) to 50. The standard library has a number of utility functions to handle Result types, safely reporting the error to the caller.
Here is a sample run of the last example:
$ rustc custom-errors.rs && ./custom-errorsErr(DivideByZeroError)50A related idiom in the standard library is the Option type, as shown in the following code snippet. This is used to indicate the nullability of an operation, indicated by the None variant. The Some variant handles the case where it holds the actual value of the type T:
pub enum Option<T> { None, Some(T),}Given this type, we could have written our divide function like this:
fn divide(dividend: u32, divisor: u32) -> Option<u32> { if divisor == 0u32 { None } else { Some(dividend / divisor) }}
fn main() { let result1 = divide(100, 0);
match result1 { None => println!("Error occurred"), Some(result) => println!("The result is {}", result), }
let result2 = divide(100, 2); println!("{:?}", result2.unwrap());}We modify our function to return an Option of type u32. In our main function, we call our function. In this case, we can match on the return type. If it happens to be None, we know that the function did not succeed. In that case, we can print an error. In case it returned Some, we extract the underlying value and print it. The second invocation works fine since we know it did not get a zero divisor. Using Option for error handling can be a bit easier to manage since it involves less boilerplate. However, this can be a bit difficult to manage in a library with custom error types since errors are not handled by the type system.
Note that Option can be represented as a Result of a given type and the unit type
type Option<T> = Result<T, ()>;.
What we have described so far for error handling has been done with recoverable errors. In some cases, though, it might be wise to abort execution if an error occurs. The standard library provides the panic! macro to handle such cases. Calling this stops the execution of the current thread, prints a message on the screen, and unwinds the call stack. However, one needs to use this cautiously since in a lot of cases, a better option is to handle the error properly and bubble the error up to the caller.
A number of built-in methods and functions call this macro in case of an error. Let’s look at the following example:
fn parse_int(s: String) -> u64 { return s.parse::<u64>().expect("Could not parse as integer")}
fn main() { // works fine let _ = parse_int("1".to_owned());
// panics let _ = parse_int("abcd".to_owned());}This fails with the following error:
thread 'main' panicked at 'Could not parse as integer: ParseIntError { kind: InvalidDigit }', src/libcore/result.rs:906:4note: Run with \`RUST_BACKTRACE=1\` for a backtrace.Some methods that call panic are expect() and unwrap().
Rust supports a macro system that has evolved quite a lot over the years. A distinctive feature of Rust macros are that they are guaranteed to not refer to identifiers outside their scope by accident, and so the macro implementation in Rust is hygienic. As one would expect, Rust macros are expanded to source code ahead of the compilation in place, and are compiled with the translation unit. The compiler enforces scoping rules on expanded macros to make them hygienic. Rust macros differ from other constructs in that they always end in an exclamation mark !.
Modern Rust has two ways of working with macros; the older, syntactic macro way, and the newer, procedural macro way. Let’s look at each of these:
This system of macros has existed as part of Rust since pre- 1.0 releases. These macros are defined using a macro called macro_rules!. Let’s look at an example:
macro_rules! factorial { ($x:expr) => { { let mut result = 1; for i in 1..($x+1) { result = result * i; } result } };}
fn main() { let arg = std::env::args().nth(1).expect("Please provide only one argument"); println!("{:?}", factorial!(arg.parse::<u64>().expect("Could not parse to an integer")));}We start with defining the factorial macro. Since we do not want the compiler to refuse to compile our code as it might overflow the macro stack, we will use a non-recursive implementation. A syntactic macro in Rust is a collection of rules where the left-hand side dictates how the rule should be matched to an input, and the right-hand side dictates what it should expand to. A rule maps to an expression on the right-hand side via the => operator. Variables local to a rule are declared using the $ sign. Match rules are expressed using a special macro language which has its own set of reserved keywords. Our declaration says that we want to take in any valid Rust expression; in this specific case, it should evaluate to an integer. We will leave it to the caller to make sure that is true. We then loop over from 1 to the last integer in the range while accumulating the result. Once done, we return back the result using the implicit return syntax.
Our caller is the main function, in that we take input from the user using the std::env module. We fetch the first in the list of inputs and throw an error if there are no inputs. We then print the result from our macro, and we try to parse the input as a u64 before passing to it. We also handle the case where parsing might fail. This works as expected:
# rustc syntactic-macro.rs && ./syntactic-macro 5120Rust also provides a few tools to debug macros. One might be interested to see what the expanded macro looks like. The trace_macros! macro does exactly that. To make it work, we will need to enable a feature gate, as shown in the following code snippet (since it is not stable in Rust yet, this code will only work in Rust nightly):
#![feature(trace_macros)]trace_macros!(true);Note that the expansion also includes println! since it is a macro defined in the standard library.
The same expansion can also be examined using the following command to invoke the compiler:
rustc -Z unstable-options —pretty expanded syntactic-macro.rs.
While regular syntactic macros are useful in a number of scenarios, some applications need advanced code generation features that are better done using the AST that the compiler operates on. Thus, there was a need to extend the macro system to include this. It was later decided that the old macro system and this new system called procedural macros would co-exist. Over time, this is intended to replace the syntactic macro system. The compiler supports loading plugins from external crates; these can receive the AST once the compiler has generated it. There are APIs available to modify the AST in-place to add new code as required. A detailed discussion of this system is beyond the scope of this book.
Rust has been inspired by functional languages such as Haskell and OCaml. Unsurprisingly, Rust has rich support for functional programming both in the language and in the standard library. In this section, we will look at some of these.
We have seen previously how Rust functions define an isolated scope in which all local variables live. Thus, variables outside the scope can never leak into it unless they are explicitly passed as arguments. There can be cases where this is not the desired behavior; closures provide an anonymous function like mechanism, which has access to all the resources defined in the scope in which it is defined. This enables the compiler to enforce the same borrow checking rules while making it easier to reuse code. In Rust terminology, a typical closure borrows all bindings of its surrounding scope. A closure can be forced to own those by marking it with the move keyword. Let’s look at some examples:
fn main() { // closure with two parameters let add = |a, b| a + b; assert_eq!(add(2, 3), 5);
// common use cases are on iterators println!("{:?}", (1..10).filter(|x| x % 2 == 0).collect::<Vec<u32>>());
// using a variable from enclosing scope let times = 2; println!("{:?}", (1..10).map(|x| x * times).collect::<Vec<i32>>());}The first example is a simple closure that adds two numbers given to it. The second example is more involved; it shows a real example of closures for functional programming. We are interested in filtering a list of integers to collect only the even ones out of it. So, we start with a range from 1 to 10, which returns an instance of the built-in type Range. Since that type implements the IntoIterator trait, that type behaves as an iterator. Thus, we can filter it by passing a closure that returns true only if the input can be divided by two. Finally, we collect the resultant iterator into a vector of u32 and print it out. The last example is similar in construction. It borrows the variable times from the closure’s enclosing scope and uses it to map to items of the range.
Let’s look at an example of using the move keyword in closures:
fn main() { let mut times = 2; { // This is in a new scope let mut borrow = |x| times += x; borrow(5); } assert_eq!(times, 7);
let mut own = move |x| times += x; own(5); assert_eq!(times, 7);
}The difference between the first closure (borrow) and the ones we have discussed so far is that this mutates the variable it inherits from the enclosing scope. We must declare the variable and the closure as mut. We also need to put the closure in a different scope so that the compiler does not complain about double borrowing when we try to assert its value. As asserted, the closure called borrow borrows the variables from its parent scope, and that’s why its original value changes to 7. The second closure called own is a move closure, thus it gets a copy of the variable times. For this to work, the variable has to implement the Copy trait so that the compiler can copy it to the closure, which all built-in types do. Since the variable that the closure gets and the original variable are not the same, the compiler does not complain about borrowing it twice. Also, the original value of the variable does not change. These types of closures are immensely important in implementing threads, as we will see in a later section. The standard library also supports accepting and returning closures in user-defined functions or methods using a number of built-in traits, as shown in the following table:
| Trait name | Function |
|---|---|
| std::ops::Fn | Implemented by closures that do not receive mutable captured variables. |
| std::ops::FnMut | Implemented by closures that need to mutate the captured variables. |
| std::ops::FnOnce | Implemented by all closures. Indicates that the closure can be called exactly once. |
Another important functional aspect is that of lazy iteration. Given a collection of types, one should be able to loop over those or a subset in any given order. In Rust, a common iterator is a range which has a start and an end. Let’s look at how these work:
#![feature(inclusive_range_syntax)]
fn main() { let numbers = 1..5; for number in numbers { println!("{}", number); } println!("------------------"); let inclusive = 1..=5; for number in inclusive { println!("{}", number); }}The first range is an exclusive range that spans from the first element to the last but one. The second range is an inclusive one which spans till the last element. Note that inclusive range is an experimental feature that might change in the future.
As one would expect, Rust does provide interfaces with which a user-defined type can be iterated on. The type just needs to implement the trait std::iterator::Iterator. Let’s look at an example. We are interested in generating the Collatz sequence (https://en.wikipedia.org/wiki/Collatz_conjecture), given an integer. This is given by the recurrence relation below, given an integer:
- If it is even, divide it by two
- If it is odd, multiply it by 3 and add one
According to the conjecture, this sequence will always terminate at 1. We will assume that is true and define our code respecting that:
// This struct holds state while iteratingstruct Collatz { current: u64, end: u64,}
// Iterator implementationimpl Iterator for Collatz { type Item = u64;
fn next(&mut self) -> Option<u64> { if self.current % 2 == 0 { self.current = self.current / 2; } else { self.current = 3 * self.current + 1; }
if self.current == self.end { None } else { Some(self.current) } }}
// Utility function to start iterationfn collatz(start: u64) -> Collatz { Collatz { current: start, end: 1u64 }}
fn main() { let input = 10;
// First 2 items for n in collatz(input).take(2) { println!("{}", n); }
// Dropping first 2 items for n in collatz(input).skip(2) { println!("{}", n); }}In our code, the state of the current iteration is represented by the struct called Collatz. We implement the Iterator protocol on it. For that, we need to implement the next function, which takes in the current state and produces the next state. When it reaches the end state, it must return a None so that the caller knows that the iterator has been exhausted. This is represented by the nullable return value of the function. Given the recurrence, the implementation is straightforward. In our main function, we instantiate the initial state and we can iterate using regular for loops. The Iterator trait automatically implements a number of useful functions; the take function takes the given number of elements from the iterator, while the skip function skips the given number of elements. All these are very important for working with iterable collections.
The following is the output of a run of our example:
$ rustc collatz.rs && ./collatz516842One of the promises of Rust is to enable fearless concurrency. Quite naturally, Rust has support for writing concurrent code through a number of mechanisms. In this chapter, we will discuss a few of these. We have seen how the Rust compiler uses borrow checking to ensure correctness of programs at compile time. It turns out that those primitives are also useful in verifying correctness of concurrent code. Now, there are multiple ways of implementing threading in a language. The simplest possible way is to create a new OS thread for each thread created in the platform. This is often called 1:1 threading. On the other hand, a number of application threads can be mapped to one OS thread. This is called N:1 threading. While this approach is resource-light since we end up with fewer actual threads, there is a higher overhead of context switches. A middle ground is called M:N threading, where multiple application threads are mapped to multiple OS level threads. This approach requires the maximum amount of safeguarding and is implemented using a runtime, something that Rust avoids. Thus, Rust uses the 1:1 model. A thread in Rust corresponds to one OS thread in contrast to languages like Go. Let’s start with a look at how Rust enables writing multithreaded applications:
use std::thread;
fn main() { for i in 1..10 { let handle = thread::spawn(move || { println!("Hello from thread number {}", i); }); let _ = handle.join(); }}We start by importing the threading library. In our main function, we create an empty vector that we will use to store references to the threads we create so that we can wait for them to exit. The threads are actually created using thread::spawn, to which we must pass a closure that will be executed in each of those threads. Since we must borrow a variable from the enclosing scope (the loop index i) in our closure, the closure itself must be a move closure. Right before exiting the closure, we call join on the current thread handle so that all threads wait for one another. This produces the following output:
# rustc threads.rs && ./threadsHello from thread number 1Hello from thread number 2Hello from thread number 3Hello from thread number 4Hello from thread number 5Hello from thread number 6Hello from thread number 7Hello from thread number 8Hello from thread number 9The real power of multithreaded applications is when threads can cooperate to do meaningful work. For that, two important things are necessary. Threads need to be able to pass data from one another and there should be ways to coordinate how the threads are scheduled so that they don’t step over one another. For the first problem, Rust provides a message, passing mechanisms via channels. Let’s look at the following example:
use std::thread;use std::sync::mpsc;
fn main() { let rhs = vec![10, 20, 30, 40, 50, 60, 70]; let lhs = vec![1, 2, 3, 4, 5, 6, 7]; let (tx, rx) = mpsc::channel();
assert_eq!(rhs.len(), lhs.len()); for i in 1..rhs.len() { let rhs = rhs.clone(); let lhs = lhs.clone(); let tx = tx.clone(); let handle = thread::spawn(move || { let s = format!("Thread {} added {} and {}, result {}", i, rhs[i], lhs[i], rhs[i] + lhs[i]); tx.clone().send(s).unwrap(); }); let _ = handle.join().unwrap(); }
drop(tx); for result in rx { println!("{}", result); }}This example is much like the previous one. We import the necessary modules to be able to work with channels. We define two vectors, and we will create a thread for each pair of elements in the two vectors so that we can add those and return the result. We create the channel, which returns handles to the sending and the receiving ends. As a safety check, we make sure that the two vectors are indeed of equal length. Then, we move on to creating our threads. Since we would need to access outside variables here, the threads need to take in a move closure like the last example. Further, the compiler will try to use the Copy trait to copy those variables to the threads. In this case, that will fail since the vector type does not implement Copy. We need to explicitly clone the resources so that they do not need to be copied. We run the computation and send the result on the sending end of the pipe. Later, we join all the threads. Before we loop over the receiving end and print the results, we need to explicitly drop the reference to the original handle to the sending end so that all senders are destroyed before we start receiving (the cloned senders will be automatically destroyed when the threads exit). This prints the following, as expected:
# rustc channels.rs && ./channelsThread 1 added 20 and 2, result 22Thread 2 added 30 and 3, result 33Thread 3 added 40 and 4, result 44Thread 4 added 50 and 5, result 55Thread 5 added 60 and 6, result 66Thread 6 added 70 and 7, result 77Also note that mpsc stands for multiple producer single consumer.
While working with multiple threads, another common idiom is that of sharing a common state between all of those. That, however, can be a can of worms in a lot of cases. The caller needs to carefully set up exclusion mechanisms so that the state is shared in a race-free manner. Luckily, the borrow checker can help in ensuring this is easier. Rust has a number of smart pointers for dealing with the shared state. The library also provides a generic mutex type that can be used as a lock while working with multiple threads. But perhaps the most important are the Send and the Sync traits. Any type that implements the Send trait can be shared safely between multiple threads. The Sync trait indicates that access from multiple threads is safe for the given data. There are a few rules around these traits:
- All built-in types implement both Send and Sync with the exception of anything unsafe, a few smart pointer types like Rc<T> and UnsafeCell<T>
- A composite type will automatically implement both, as long as it does not have any type that does not implement Send and Sync
The std::sync package has a lot of types and helpers for working with parallel code.
In the previous paragraph, we mentioned unsafe Rust. Let’s take a detour and look at that in a bit more detail. The Rust compiler provides some strong guarantees around safe programming by using a robust type system. However, there can be cases where these become more of an overhead. To handle such cases, the language provides a way to opt out of those guarantees. A block of code marked with the unsafe keyword can do everything Rust can do, and the following:
- Dereference raw pointer types (*mut T or *const T)
- Call unsafe functions or methods
- Implement a trait marked as unsafe
- Mutate a static variable
Let’s look at an example which uses the unsafe block of code to dereference a pointer:
fn main() { let num: u32 = 42; let p: *const u32 = #
unsafe { assert_eq!(*p, num); }}Here, we create a variable and a pointer to it; if we try to dereference the pointer without using the unsafe block, the compiler will refuse to compile. Inside the unsafe block, we get back the original value on dereferencing. While unsafe code can be dangerous to work with, it’s very useful in lower level programming like Kernel (RedoxOS) and embedded systems.
Rust treats testing as a first-class construct; all tools in the ecosystem supports testing. The compiler provides a built-in configuration attribute that designates a module for testing. There is also a test attribute that designates functions as tests. When Cargo generates a project from scratch, it sets up this boilerplate. Let’s look at an example project; we will call it factorial. It will export a macro that computes the factorial given an integer. Since we have conveniently written such a macro before, we will just re-use that code here. Note that since this crate will be used as a library, this does not have a main function:
# cargo new factorial --lib# cargo test Compiling factorial v0.1.0 (file:///Users/Abhishek/Desktop/rust-book/src/ch2/factorial) Finished dev [unoptimized + debuginfo] target(s) in 1.6 secs Running target/debug/deps/factorial-364286f171614349
running 1 testtest tests::it_works ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
Doc-tests factorial
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered outRunning cargo test runs the stub tests that Cargo generates for us. We will copy the code for the factorial macro to the lib.rs, which will look like this:
#[allow(unused_macros)]#[macro_export]macro_rules! factorial { ($x:expr) => { { let mut result = 1; for i in 1..($x+1) { result = result * i; } result } };}
#[cfg(test)]mod tests { #[test] fn test_factorial() { assert_eq!(factorial!(5), 120); }}We also added a test to make sure factorial actually works as one would expect. The #[macro_export] attribute tells the compiler that this macro is to be used outside the crate. The compiler built-in assert_eq! macro checks that the two arguments are indeed equal. We also need to put the #[allow(unused_macros)] attribute since, without it, the compiler will complain that the macro is not being used in non-test code. If we add one more test that looks like this:
#[test]fn test_factorial_fail() { assert_eq!(factorial!(5), 121);}This is obviously wrong, and as expected, fails and gives us a descriptive error. The compiler also supports an attribute called #[should_panic] that marks tests that should panic. In this case, the tests pass only if there is a panic. Another way of writing tests is in the documentation which is also run on a Cargo invocation.
This is a very important tool in documenting code with working examples, which are guaranteed to work as the codebase evolves. Let’s go ahead and add some doctest for our factorial macro:
/// The factorial crate provides a macro to compute factorial of a given/// integer/// # Examples////// \`\`\`/// # #[macro_use] extern crate factorial;/// # fn main() {/// assert_eq!(factorial!(0), 1);/// assert_eq!(factorial!(6), 720);/// # }/// \`\`\`///
#[macro_export]macro_rules! factorial { ($x:expr) => { { let mut result = 1; for i in 1..($x+1) { result = result * i; } result } };}Doctests for macros differ a bit from doctests for everything else in the following way:
- They must use the #[macro_use] attribute to mark that the macro is being used here. Note that an external crate that depends on the crate that exports a macro must use that attribute too.
- They must define the main function and include an extern crate directive in the doctests. For everything else, the compiler generates the main function as needed. The extra # marks hide those from the generated documentation.
In general, the tests module, doctests, and the #[test] attributes should be used only for unit tests. Integration tests should be placed in a top-level tests directory.
The Rust team is working on adding support for running benchmarks in the test system. This is only available on nightly for now.
This chapter was a very short introduction to the Rust language and the ecosystem. Given this background in Rust, let’s look at a frequently asked question: should a company adopt Rust? Like a lot of things in engineering, the correct answer is that it depends on a lot of factors. One of the primary reasons for adopting Rust would be the ability to write robust code with less of a footprint as possible. Thus, Rust is suitable for projects targeting embedded devices. This area has traditionally used assembly, C, and C++. Rust can provide the same performance guarantees while ensuring code correctness. Rust also works well for offloading performance intensive computation from Python or Ruby. The primary pain point with Rust is that the learning curve can be steep. Thus, a team trying to adopt Rust might spend a lot of time fighting with the compiler, trying to run code. This, however, eases out with time. Luckily, the compiler error messages are generally very helpful. In 2017, the Rust team decided to make ergonomics a priority. This push has made onboarding new developers a lot easier. For large Rust projects, compile time can be larger than C, C++, or Go. This can become a problem for some teams. There are a few ways to work around this problem, one of them being incremental compilation. Thus, it is difficult to arrive at a one size fits all solution. Hopefully, this short introduction will help in deciding whether to choose Rust in a new project.
In the next chapter, we will build on what we studied here by looking at how Rust handles TCP and UDP connections between two hosts in a network.