Introduction

Welcome to “The Rust Programming Language,” an introductory book about Rust. Rust is a programming language that’s focused on safety, concurrency, and speed. It maintains these goals without having a garbage collector, making it a useful language for a number of use cases other languages aren’t good at: embedding in other languages, programs with specific space and time requirements, and writing low-level code, like device drivers and operating systems. It improves on current languages targeting this space by having a number of compile-time safety checks that produce no runtime overhead, while eliminating all data races. Rust also aims to achieve ‘zero-cost abstractions’ even though some of these abstractions feel like those of a high-level language. Even then, Rust still allows precise control like a low-level language would.

This book is written for a reader who already knows how to program in at least one programming language. Which language that is does not matter very much, though you may have an easier time if you’ve programmed in a low-level language with manual memory allocation.

After reading this book, you should be comfortable writing Rust programs. We’ll be learning Rust through small, focused examples that demonstrate each topic. The chapters build upon each other, so if you skip ahead, you may have to skip back to refer to a previous concept.

Contributing to the book

This book is open source. If you find an error, please don’t hesitate to file an issue or send a pull request on GitHub.

Installation

The first step to using Rust is to install it. Generally speaking, you’ll need an Internet connection to run the commands in this chapter, as we’ll be downloading Rust from the internet.

We’ll be showing off a number of commands using a terminal, and those lines all start with $. We don't need to type in the $s, they are there to indicate the start of each command. We’ll see many tutorials and examples around the web that follow this convention: $ for commands run as our regular user, and # for commands we should be running as an administrator.

Installing on Linux or Mac

If we're on Linux or a Mac, all we need to do is open a terminal and type this:

$ curl -sSf https://static.rust-lang.org/rustup.sh | sh

This will download a script, and stat the installation. If it all goes well, you’ll see this appear:

Welcome to Rust.

This script will download the Rust compiler and its package manager, Cargo, and
install them to /usr/local. You may install elsewhere by running this script
with the --prefix=<path> option.

The installer will run under ‘sudo’ and may ask you for your password. If you do
not want the script to run ‘sudo’ then pass it the --disable-sudo flag.

You may uninstall later by running /usr/local/lib/rustlib/uninstall.sh,
or by running this script again with the --uninstall flag.

Continue? (y/N) 

From here, press y for ‘yes’, and then follow the rest of the prompts.

Installing on Windows

If you're on Windows, please download the appropriate installer.

Uninstalling

Uninstalling Rust is as easy as installing it. On Linux or Mac, just run the uninstall script:

$ sudo /usr/local/lib/rustlib/uninstall.sh

If we used the Windows installer, we can re-run the .msi and it will give us an uninstall option.

Troubleshooting

If we've got Rust installed, we can open up a shell, and type this:

$ rustc --version

You should see the version number, commit hash, and commit date.

If you do, Rust has been installed successfully! Congrats!

If you don't and you're on Windows, check that Rust is in your %PATH% system variable. If it isn't, run the installer again, select "Change" on the "Change, repair, or remove installation" page and ensure "Add to PATH" is checked.

If not, there are a number of places where we can get help. The easiest is the #rust IRC channel on irc.mozilla.org, which we can access through Mibbit. Click that link, and we'll be chatting with other Rustaceans (a silly nickname we call ourselves) who can help us out. Other great resources include the user’s forum, and Stack Overflow.

This installer also installs a copy of the documentation locally, so we can read it offline. On UNIX systems, /usr/local/share/doc/rust is the location. On Windows, it's in a share/doc directory, inside the directory to which Rust was installed.

Hello, world!

Now that you have Rust installed, let’s write your first Rust program. It's traditional when learning a new language to write a little program to print the text “Hello, world!” to the screen, and in this section, we'll follow that tradition.

The nice thing about starting with such a simple program is that you can quickly verify that your compiler is installed, and that it's working properly. Printing information to the screen is also just a pretty common thing to do, so practicing it early on is good.

Note: This book assumes basic familiarity with the command line. Rust itself makes no specific demands about your editing, tooling, or where your code lives, so if you prefer an IDE to the command line, that's an option.

Creating a Project File

First, make a file to put your Rust code in. Rust doesn't care where your code lives, but for this book, I suggest making a projects directory in your home directory, and keeping all your projects there. Open a terminal and enter the following commands to make a directory for this particular project:

$ mkdir ~/projects
$ cd ~/projects
$ mkdir hello_world
$ cd hello_world

Note: If you’re on Windows and not using PowerShell, the ~ may not work. Consult the documentation for your shell for more details.

Writing and Running a Rust Program

Next, make a new source file and call it main.rs. Rust files always end in a .rs extension. If you’re using more than one word in your filename, use an underscore to separate them; for example, you'd use hello_world.rs rather than helloworld.rs.

Now open the main.rs file you just created, and type the following code:

fn main() {
    println!("Hello, world!");
}

Save the file, and go back to your terminal window. On Linux or OSX, enter the following commands:

$ rustc main.rs
$ ./main 
Hello, world!

In Windows, just replace main with main.exe. Regardless of your operating system, you should see the string Hello, world! print to the terminal. If you did, then congratulations! You've officially written a Rust program. That makes you a Rust programmer! Welcome.

Anatomy of a Rust Program

Now, let’s go over what just happened in your "Hello, world!" program in detail. Here's the first piece of the puzzle:

fn main() {

}

These lines define a function in Rust. The main function is special: it's the beginning of every Rust program. The first line says, “I’m declaring a function named main that takes no arguments and returns nothing.” If there were arguments, they would go inside the parentheses (( and )), and because we aren’t returning anything from this function, we can omit the return type entirely.

Also note that the function body is wrapped in curly braces ({ and }). Rust requires these around all function bodies. It's considered good style to put the opening curly brace on the same line as the function declaration, with one space in between.

Inside the main() function:

    println!("Hello, world!");

This line does all of the work in this little program: it prints text to the screen. There are a number of details that are important here. The first is that it’s indented with four spaces, not tabs.

The second important part is the println!() line. This is calling a Rust macro, which is how metaprogramming is done in Rust. If it were calling a function instead, it would look like this: println() (without the !). We'll discuss Rust macros in more detail later, but for now you just need to know that when you see a ! that means that you’re calling a macro instead of a normal function.

Next is "Hello, world!" which is a string. We pass this string as an argument to println!, which prints the string to the screen. Easy enough!

The line ends with a semicolon (;). Rust is an expression oriented language, which means that most things are expressions, rather than statements. The ; indicates that this expression is over, and the next one is ready to begin. Most lines of Rust code end with a ;.

Compiling and Running Are Separate Steps

In "Writing and Running a Rust Program", we showed you how to run a newly created program. We'll break that process down and examine each step now.

Before running a Rust program, you have to compile it. You can use the Rust compiler by entering the rustc command and passing it the name of your source file, like this:

$ rustc main.rs

If you come from a C or C++ background, you'll notice that this is similar to gcc or clang. After compiling successfully, Rust should output a binary executable, which you can see on Linux or OSX by entering the ls command in your shell as follows:

$ ls
main  main.rs

On Windows, you'd enter:

$ dir
main.exe  main.rs

This shows we have two files: the source code, with an .rs extension, and the executable (main.exe on Windows, main everywhere else). All that's left to do from here is run the main or main.exe file, like this:

$ ./main  # or main.exe on Windows

If main.rs were your "Hello, world!" program, this would print Hello, world! to your terminal.

If you come from a dynamic language like Ruby, Python, or JavaScript, you may not be used to compiling and running a program being separate steps. Rust is an ahead-of-time compiled language, which means that you can compile a program, give it to someone else, and they can run it even without Rust installed. If you give someone a .rb or .py or .js file, on the other hand, they need to have a Ruby, Python, or JavaScript implementation installed (respectively), but you only need one command to both compile and run your program. Everything is a tradeoff in language design.

Just compiling with rustc is fine for simple programs, but as your project grows, you'll want to be able to manage all of the options your project has, and make it easy to share your code with other people and projects. Next, I'll introduce you to a tool called Cargo, which will help you write real-world Rust programs.

Hello, Cargo!

Cargo is Rust’s build system and package manager, and Rustaceans use Cargo to manage their Rust projects. Cargo manages three things: building your code, downloading the libraries your code depends on, and building those libraries. We call libraries your code needs ‘dependencies’ since your code depends on them.

The simplest Rust programs don’t have any dependencies, so right now, you'd only use the first part of its functionality. As you write more complex Rust programs, you’ll want to add dependencies, and if you start off using Cargo, that will be a lot easier to do.

As the vast, vast majority of Rust projects use Cargo, we will assume that you’re using it for the rest of the book. Cargo comes installed with Rust itself, if you used the official installers. If you installed Rust through some other means, you can check if you have Cargo installed by typing:

$ cargo --version

Into a terminal. If you see a version number, great! If you see an error like ‘command not found’, then you should look at the documentation for the system in which you installed Rust, to determine if Cargo is separate.

Converting to Cargo

Let’s convert the Hello World program to Cargo. To Cargo-fy a project, you need to do three things:

  1. Put your source file in the right directory.
  2. Get rid of the old executable (main.exe on Windows, main everywhere else) and make a new one.
  3. Make a Cargo configuration file.

Let's get started!

Creating a new Executable and Source Directory

First, go back to your terminal, move to your hello_world directory, and enter the following commands:

$ mkdir src
$ mv main.rs src/main.rs
$ rm main  # or 'del main.exe' on Windows

Cargo expects your source files to live inside a src directory, so do that first. This leaves the top-level project directory (in this case, hello_world) for READMEs, license information, and anything else not related to your code. In this way, using Cargo helps you keep your projects nice and tidy. There's a place for everything, and everything is in its place.

Now, copy main.rs to the src directory, and delete the compiled file you created with rustc. As usual, replace main with main.exe if you're on Windows.

This example retains main.rs as the source filename because it's creating an executable. If you wanted to make a library instead, you'd name the file lib.rs. This convention is used by Cargo to successfully compile your projects, but it can be overridden if you wish.

Creating a Configuration File

Next, create a new file inside your hello_world directory, and call it Cargo.toml.

Make sure to capitalize the C in Cargo.toml, or Cargo won't know what to do with the configuration file.

This file is in the TOML (Tom's Obvious, Minimal Language) format. TOML is similar to INI, but has some extra goodies, and is used as Cargo’s configuration format.

Inside this file, type the following information:

[package]

name = "hello_world"
version = "0.0.1"
authors = [ "Your name <you@example.com>" ]

The first line, [package], indicates that the following statements are configuring a package. As we add more information to this file, we’ll add other sections, but for now, we just have the package configuration.

The other three lines set the three bits of configuration that Cargo needs to know to compile your program: its name, what version it is, and who wrote it.

Once you've added this information to the Cargo.toml file, save it to finish creating the configuration file.

Building and Running a Cargo Project

With your Cargo.toml file in place in your project's root directory, you should be ready to build and run your Hello World program! To do so, enter the following commands:

$ cargo build
   Compiling hello_world v0.0.1 (file:///home/yourname/projects/hello_world)
$ ./target/debug/hello_world
Hello, world!

Bam! If all goes well, Hello, world! should print to the terminal once more.

You just built a project with cargo build and ran it with ./target/debug/hello_world, but you can actually do both in one step with cargo run as follows:

$ cargo run
     Running `target/debug/hello_world`
Hello, world!

Notice that this example didn’t re-build the project. Cargo figured out that the file hasn’t changed, and so it just ran the binary. If you'd modified your source code, Cargo would have rebuilt the project before running it, and you would have seen something like this:

$ cargo run
   Compiling hello_world v0.0.1 (file:///home/yourname/projects/hello_world)
     Running `target/debug/hello_world`
Hello, world!

Cargo checks to see if any of your project’s files have been modified, and only rebuilds your project if they’ve changed since the last time you built it.

With simple projects, Cargo doesn't bring a whole lot over just using rustc, but it will become useful in future. With complex projects composed of multiple crates, it’s much easier to let Cargo coordinate the build. With Cargo, you can just run cargo build, and it should work the right way.

Building for Release

When your project is finally ready for release, you can use cargo build --release to compile your project with optimizations. These optimizations make your Rust code run faster, but turning them on makes your program take longer to compile. This is why there are two different profiles, one for development, and one for building the final program you’ll give to a user.

Running this command also causes Cargo to create a new file called Cargo.lock, which looks like this:

[root]
name = "hello_world"
version = "0.0.1"

Cargo uses the Cargo.lock file to keep track of dependencies in your application. This is the Hello World project's Cargo.lock file. This project doesn't have dependencies, so the file is a bit sparse. Realistically, you won't ever need to touch this file yourself; just let Cargo handle it.

That’s it! If you've been following along, you should have successfully built hello_world with Cargo.

Even though the project is simple, it now uses much of the real tooling you’ll use for the rest of your Rust career. In fact, you can expect to start virtually all Rust projects with some variation on the following commands:

$ git clone someurl.com/foo
$ cd foo
$ cargo build

Making A New Cargo Project the Easy Way

You don’t have to go through that previous process every time you want to start a new project! Cargo can quickly make a bare-bones project directory that you can start developing in right away.

To start a new project with Cargo, enter cargo new at the command line:

$ cargo new hello_world --bin

This command passes --bin because the goal is to get straight to making an executable application, as opposed to a library. Executables are often called binaries (as in /usr/bin, if you’re on a Unix system).

Cargo has generated two files and one directory for us: a Cargo.toml and a src directory with a main.rs file inside. These should look familliar, they’re exactly what we created by hand, above.

This output is all you need to get started. First, open Cargo.toml. It should look something like this:

[package]

name = "hello_world"
version = "0.1.0"
authors = ["Your Name <you@example.com>"]

Cargo has populated Cargo.toml with reasonable defaults based on the arguments you gave it and your git global configuration. You may notice that Cargo has also initialized the hello_world directory as a git repository.

Here’s what should be in src/main.rs:

fn main() {
    println!("Hello, world!");
}

Cargo has generated a "Hello World!" for you, and you’re ready to start coding!

Note: If you want to look at Cargo in more detail, check out the official Cargo guide, which covers all of its features.

The Design of Rust

Tutorial

Primitive Rust

We’ll start our journey with Rust by talking about the absolute basics — concepts that appear in almost every programming language. Many programming languages have lots in common at their core. None of the concepts presented are unique to Rust, but we’ll cover Rust’s particular syntax and conventions around these common concepts.

If you want to skip this section, you can, but you may end up coming back later to find out small details. These foundations will be in every single useful Rust program, and learning them gives us a strong core to start from.

Variable Bindings

The foundation of virtually every program is the ability to store and modify data. Rust programs are no different. Let’s start with a short example.

The basics of bindings

First, we’ll generate a new project with Cargo. Open a terminal, and navigate to the directory where you’d like to keep your projects. From there, let’s generate a new project:

$ cargo new --bin bindings
$ cd bindings

This creates a new project, ‘bindings’, and sets up our Cargo.toml and src/main.rs files. As we saw in “Hello, World!”, Cargo will generate these files and create a little ‘hello world’ program for us:

fn main() {
    println!("Hello, world!");
}

Let’s replace that program with this one:

fn main() {
    let x = 5;

    println!("The value of x is: {}", x);
}

And finally, run it:

$ cargo run
   Compiling bindings v0.1.0 (file:///home/steve/tmp/bindings)
     Running `target/debug/bindings`
The value of x is: 5

If you see an error instead, double check that you have copied the program exactly as written. Let’s break this down, line by line.

fn main() {

The main() function is the entry point of every Rust program. We’ll talk more about functions in the next section, but for now, all we need to know is that this is where our program begins. The opening curly brace, {, indicates the start of the function’s body.

    let x = 5;

This is our first ‘variable binding’, which we create with a ‘let statement’.

This let statement has this form:

let NAME = EXPRESSION;

A let statement first evaluates the EXPRESSION, and then binds the resulting value to NAME so that it can be referred to later in the program. In our simple example, the expression was already a value, 5, but we could achieve the same effect with:

let x = 2 + 3;

In general, let statements work with patterns; a name is a particularly humble form of pattern. Patterns are a big part of Rust, we’ll see more complex and powerful patterns as we go along.

Before we do that, though, let’s finish investigating this example. Here’s the next line:

    println!("The value of x is: {}", x);

The println! macro prints text to the screen. We can tell that it’s a macro due to the !. We won’t learn how to write macros until much later in the book, but we’ll use macros provided by the standard library throughout. Every time you see a !, remember that it signifies a macro. Macros can add new syntax to the language, and the ! is a reminder that things may look slightly unusual.

println!, specifically, has one required argument, a ‘format string’, and zero or more optional arguments. The format string can contain the special text {}. Each instance of {} corresponds to an additional argument. Here’s an example:

let x = 2 + 3;
let y = x + 5;
println!("The value of x is {}, and the value of y is {}", x, y);

You can think of {} as little crab pincers, holding the value in place. This placeholder has a number of more advanced formatting options that we’ll discuss later.

}

Finally, a closing curly brace matches up with the opening curly brace that declared the main() function, and declares its end.

This explains our output:

The value of x is: 5

We assign 5 to a binding, x, and then print it to the screen with println!.

Multiple binding

Let’s try a more complex pattern. Change our example program to this:

fn main() {
    let (x, y) = (5, 6);

    println!("The value of x is: {}", x);
    println!("The value of y is: {}", y);
}

And run it with cargo run:

$ cargo run
   Compiling bindings v0.1.0 (file:///home/steve/tmp/bindings)
     Running `target/debug/bindings`
The value of x is: 5
The value of y is: 6

We’ve created two bindings with one let! Here’s our pattern:

(x, y)

And here’s the value:

(5, 6)

As you can see, the two line up visually, and so let binds 5 to x and 6 to y. We could have used two let statements as well:

fn main() {
    let x = 5;
    let y = 6;
}

In simple cases like this, two lets may be clearer, but in others, creating multiple bindings at once is nice. As we become more proficient in Rust, we’ll figure out which style is better, but it’s mostly a judgement call.

Type annotations

You may have noticed that we didn’t declare the type of x or y in our previous examples. Rust is a statically typed language, which means that at compile time, we must know the types of all bindings. But annotating every single binding with a type can feel like busywork, and make code noisy. To solve this issue, Rust uses ‘type inference’, meaning that it attempts to infer the types of your bindings.

The primary way that the type is inferred is by looking at how it is used. Let’s look at the example again:

fn main() {
    let x = 5;
}

When we bind x to 5, the compiler knows that x should be a numeric type. Without any other information, it defaults to i32, a thirty-two bit integer type. We’ll talk more about Rust’s basic types in section 3.3.

Here’s what a let statement with a ‘type annotation’ looks like:

fn main() {
    let x: i32 = 5;
}

We can add a colon, followed by the type name. Here’s the structure of a let statement with a type annotation:

let PATTERN: TYPE = VALUE;

Note that the colon and the TYPE go after the PATTERN, not in the pattern itself. As an example, here’s our more complex pattern with two bindings:

fn main() {
    let (x, y): (i32, i32) = (5, 6);
}

Just like we match up the VALUE with the PATTERN, we match up the TYPE with the PATTERN.

Delayed Initialization

We do not have to provide bindings with an initial value, and can assign it later. Try this program:

fn main() {
    let x;

    x = 5;

    println!("The value of x is: {}", x);
}

And run it with cargo run:

$ cargo run
   Compiling bindings v0.1.0 (file:///home/steve/tmp/bindings)
     Running `target/debug/bindings`
The value of x is: 5

It’s all good. This raises a question, though: what if we try to print out a binding before we declare a value? Here’s a program that demonstrates this question:

fn main() {
    let x;

    println!("The value of x is: {}", x);

    x = 5;
}

We can find out the answer with cargo run:

   Compiling bindings v0.1.0 (file:///home/steve/tmp/bindings)
src/main.rs:4:39: 4:40 error: use of possibly uninitialized variable: `x` [E0381]
src/main.rs:4     println!(“The value of x is: {}”, x);
                                                    ^
<std macros>:2:25: 2:56 note: in this expansion of format_args!
<std macros>:3:1: 3:54 note: in this expansion of print! (defined in <std macros>)
src/main.rs:4:5: 4:42 note: in this expansion of println! (defined in <std macros>)
src/main.rs:4:39: 4:40 help: run `rustc --explain E0381` to see a detailed explanation
error: aborting due to previous error
Could not compile `bindings`.

To learn more, run the command again with --verbose.

An error! The compiler won’t let us write a program like this. This is our first example of the compiler helping us find an error in our program. Different programming languages have different ways of approaching this problem. Some languages always initialize values with some sort of default. Other languages leave the value uninitialized, and make no promises about what happens if you try to use something before initialization. Rust chooses something else: error and force the programmer to explain what they want. We must do some sort of initialization before we can use x.

Extended error explanations

There’s one more interesting part of this error message:

src/main.rs:4:39: 4:40 help: run `rustc --explain E0381` to see a detailed explanation

We can see an extended explanation by passing the --explain flag to rustc. Not every error has a longer explanation, but many of them do. These extended explanations try to show off common ways that the error occurs, and common solutions to the issue. Here’s E0381:

$ rustc --explain E0381
It is not allowed to use or capture an uninitialized variable. For example:

fn main() {
    let x: i32;
    let y = x; // error, use of possibly uninitialized variable

To fix this, ensure that any declared variables are initialized before being
used.

These explanations can really help if you’re stuck on an error. The compiler is your friend, and is here to help.

Mutable bindings

What about changing the value of a binding? Here’s another sample program that asks this question:

fn main() {
    let x = 5;

    x = 6;

    println!("The value of x is: {}", x);
}

cargo run has the answer for us:

$ cargo run
   Compiling bindings v0.1.0 (file:///home/steve/tmp/bindings)
src/main.rs:4:5: 4:10 error: re-assignment of immutable variable `x` [E0384]
src/main.rs:4     x = 6;
                  ^~~~~
src/main.rs:4:5: 4:10 help: run `rustc --explain E0384` to see a detailed explanation
src/main.rs:2:9: 2:10 note: prior assignment occurs here
src/main.rs:2     let x = 5;
                      ^

The error mentions re-assigment of immutable variable. That’s right: bindings are immutable. But they’re only immutable by default. In a pattern, when we’re creating a new name, we can add mut in front to make the binding a mutable one. Here’s an example:

fn main() {
    let mut x = 5;

    println!("The value of x is: {}", x);

    x = 6;

    println!("The value of x is: {}", x);
}

Running this, we get:

$ cargo run
   Compiling bindings v0.1.0 (file:///home/steve/tmp/bindings)
     Running `target/debug/bindings`
The value of x is: 5
The value of x is: 6

We can now change the value that x binds to. Note that the syntax is not let mut exactly; it’s using mut in a pattern. This becomes more obvious with our () pattern:

fn main() {
    let (mut x, y) = (5, 6);

    x = 7;
    y = 8;
}

The compiler will complain about this program:

$ cargo build
   Compiling bindings v0.1.0 (file:///home/steve/tmp/bindings)
src/main.rs:5:5: 5:10 error: re-assignment of immutable variable `y` [E0384]
src/main.rs:5     y = 8;
                  ^~~~~
src/main.rs:5:5: 5:10 help: run `rustc --explain E0384` to see a detailed explanation
src/main.rs:2:17: 2:18 note: prior assignment occurs here
src/main.rs:2     let (mut x, y) = (5, 6);
                              ^

It’s fine with re-assigning x, but not y. The mut only applies to the name that follows it, not the whole pattern.

Reassignment, not mutation

There is one subtlety we haven’t covered yet: mut allows you to mutate the binding, but not what the binding binds to. In other words:

fn main() {
    let mut x = 5;

    x = 6;
}

This is not changing the value that x is bound to, but creating a new value, 6, and changing the binding to bind to it instead. It’s a subtle but important difference. Well, for now, it does not make a lot of difference, but when our programs get more complex, it will. Specifically, passing arguments to functions will illustrate the difference. We’ll talk about that in the next section, when we discuss functions.

Scope

Variable bindings have a ‘scope’ in which they’re valid. That scope begins from the point at which the binding is declared, and ends at the end of the next block of code. We can only access bindings which are ‘in scope’. We cannot access them ‘before they come into scope’ or ‘after they go out of scope’. Here’s an example:

fn main() {
    println!("x is not yet in scope");

    let x = 5;
    println!("x is now in scope");

    println!("In real code, we’d now do a bunch of work."); 
    
    println!("x will go out of scope now! The next curly brace is ending the main function.");
}

We can create arbitrary scopes through the use of { and }:

fn main() {
    println!("x is not yet in scope");

    let x = 5;
    println!("x is now in scope");

    println!("Let’s start a new scope!");

    {
        let y = 5;
        println!("y is now in scope");
        println!("x is also still in scope");

        println!("y will go out of scope now!");
        println!("The next curly brace is ending the scope we started.");
    }

    println!("x is still in scope, but y is now out of scope and is not usable");
    
    println!("x will go out of scope now! The next curly brace is ending the main function.");
}

What bindings are in and out of scope will become much more important later, once we learn about ‘references’ and ‘traits’.

Shadowing

A final thing about bindings: they can ‘shadow’ previous bindings with the same name. Here’s a sample program:

fn main() {
    let x = 5;
    let x = 6;

    println!("The value of x is: {}", x);
}  

Running it, we can see the shadowing in action:

src/main.rs:2:9: 2:10 warning: unused variable: `x`, #[warn(unused_variables)] on by default
src/main.rs:2     let x = 5;
                      ^
     Running `target/debug/bindings`
The value of x is: 6

There are two interesting things in this output. First, Rust will compile and run this program, no problem. And as we can see, the value of x is 6. But we didn’t declare x as mutable. Instead, we declared a new binding that is also named x, and gave it a new value. The older value that we bound x to is inaccessible as soon as the new x is declared. This can be useful if you’d like to perform a few transformations on a value, and leave it immutable. For example:

fn main() {
    let x = 5;
    let x = x + 1;
    let x = x * 2;

    println!("The value of x is: {}", x);
}

This will print:

   Compiling bindings v0.1.0 (file:///home/steve/tmp/bindings)
     Running `target/debug/bindings`
The value of x is: 12

This lets us modify x, but not deal with mutation. This is nice because we know that the compiler will let us know if we try to modify it later. Let’s assume that after we calculate 12, we don’t want to modify x again. If we had written this program in a mutable style, like this:

fn main() {
    let mut x = 5;
    x = x + 1;
    x = x * 2;

    println!("The value of x is: {}", x);

    x = 15;

    println!("The value of x is: {}", x);
}

Rust is happy to let us mutate it again, to 15. A similar program in our immutable style will let us know about that accidental mutation, however:

fn main() {
    let x = 5;
    let x = x + 1;
    let x = x * 2;

    println!("The value of x is: {}", x);

    x = 15;

    println!("The value of x is: {}", x);
}

If we try to compile, we get an error:

$ cargo build
   Compiling bindings v0.1.0 (file:///home/steve/tmp/bindings)
src/main.rs:8:5: 8:11 error: re-assignment of immutable variable `x` [E0384]
src/main.rs:8     x = 15;
                  ^~~~~~
src/main.rs:8:5: 8:11 help: run `rustc --explain E0384` to see a detailed explanation
src/main.rs:4:9: 4:10 note: prior assignment occurs here
src/main.rs:4     let x = x * 2;
                      ^
error: aborting due to previous error
Could not compile `bindings`.

Exactly what we wanted.

Shadowing can take some time to get used to, but it’s very powerful, and works well with immutability.

There was one more thing we should talk about in the output from compiling our initial program. It’s this part:

src/main.rs:2:9: 2:10 warning: unused variable: `x`, #[warn(unused_variables)] on by default

Here’s the two lines of relevant code:

let x = 5;
let x = 6;

Rust knows that we shadowed x, but we never ended up using the initial value. This isn’t wrong, exactly, it just may not have been what we wanted. In this case, the compiler issues a ‘warning’, but still compiles our program. The #[warn(unused_variables)] syntax is called an ‘attribute’, which we’ll discuss in a later section. More specifically, a warning like this is called a ‘lint’, which is an old term for the bits of sheep’s wool that you wouldn’t want to put in cloth. Similarly, this lint is telling us that we may have an extra bit of code we don’t need. Our program would work just fine without it. It’s worth listening to these warnings, and fixing the problems they point out. They can be signs of a larger problem. In this case, we may not have realized that we were shadowing x.

Shadowing and scopes

Like any binding, a binding that shadows another binding will go away at the end of a scope. Here’s an example program:

fn main() {
    let x = 5;

    println!("Before shadowing, x is: {}", x);

    {
        let x = 6;

        println!("Now that x is shadowed, x is: {}", x);
    }

    println!("After shadowing, x is: {}", x);
}

If we run this example, we can see the shadow appear and disappear:

$ cargo run
   Compiling bindings v0.1.0 (file:///home/steve/tmp/bindings)
     Running `target/debug/bindings`
Before shadowing, x is: 5
Now that x is shadowed, x is: 6
After shadowing, x is: 5

Functions

Functions are pervasive in Rust code. We’ve already seen the most important function, main(), in previous sections of the book:

fn main() {
    println!("Hello, world!");
}

We can declare new functions with the fn keyword:

fn another_function() {
    println!("Another function.");
}

Rust code uses snake_case as a style for function names: all lower case, with underscores separating words. We can can call any function we’ve defined by using its name and some parenthesis:

fn main() {
    println!("Hello, world!");

    another_function();
}

fn another_function() {
    println!("Another function.");
}

Let’s start a new project to explore functions. Open a terminal, and navigate to the directory where you’d like to keep your projects. From there, use Cargo to generate a new project:

$ cargo new --bin functions
$ cd functions

Place the new example in src/main.rs, and run it:

$ cargo run
   Compiling functions v0.1.0 (file:///home/steve/tmp/functions)
     Running `target/debug/functions`
Hello, world!
Another function.

As we can see, the lines execute in order: first, we print out our “Hello, world!” message, and then another_function() is called. It then prints its message as well.

Function Arguments

Functions can also take arguments:

fn main() {
    another_function(5);
}

fn another_function(x: i32) {
    println!("The value of x is: {}", x);
}

Let’s try running it:

$ cargo run
   Compiling functions v0.1.0 (file:///home/steve/tmp/functions)
     Running `target/debug/functions`
The value of x is: 5

Let’s take a closer look at another_function()’s signature:

fn another_function(x: i32) {

Declaring a function which takes a single argument looks like this:

fn NAME(PATTERN) {

That’s right, patterns appear again. Consider how the parameter declaration here looks like the let bindings we used earlier:

let x: i32;
fn another_function(x: i32) {

There’s only one difference here: in function signatures, we must declare the type. This is a deliberate decision; we find that requiring type annotations in functions means that you almost never need them anywhere else.

You can separate multiple arguments with a comma:

fn NAME(PATTERN, PATTERN, PATTERN, PATTERN...) {

Here’s a full example:

fn main() {
    another_function(5, 6);
}

fn another_function(x: i32, y: i32) {
    println!("The value of x is: {}", x);
    println!("The value of y is: {}", y);
}

Let’s try it:

$ cargo run
   Compiling functions v0.1.0 (file:///home/steve/tmp/functions)
     Running `target/debug/functions`
The value of x is: 5
The value of y is: 6

We could also create bindings, and pass them in as arguments:

fn main() {
    let a = 5;
    let b = 6;

    another_function(a, b);
}

fn another_function(x: i32, y: i32) {
    println!("The value of x is: {}", x);
    println!("The value of y is: {}", y);
}

This has the same effect:

$ cargo run
   Compiling functions v0.1.0 (file:///home/steve/tmp/functions)
     Running `target/debug/functions`
The value of x is: 5
The value of y is: 6

Note that our bindings are called a and b, yet inside of the function, we refer to them by the names in the signature, x and y. Inside a function, only its parameters are in scope, so we need to use those names. Bindings passed as parameters don’t need to have the same name as the arguments.

Return values

Functions can also return values back to the function that called them:

fn NAME(PATTERN, PATTERN, PATTERN, PATTERN...) -> TYPE {

We don’t name return values, but we do declare their type, after an arrow: ->. Here’s a sample program:

fn main() {
    let x = five();

    println!("The value of x is: {}", x);
}

fn five() -> i32 {
    5
}

Let’s try running it:

$ cargo run
   Compiling functions v0.1.0 (file:///home/steve/tmp/functions)
     Running `target/debug/functions`
The value of x is: 5

Let’s examine this in more detail. There are two important bits. First, we can use the return value of a function to initialize a binding:

let x = five();

Because five() returns a 5, this is the same as:

let x = 5;

The second interesting bit is five() itself:

fn five() -> i32 {
    5
}

We have no arguments, and our return type, i32. However, the body of this function is a lonely 5. There’s a detail here that you may or may not have noticed: we’ve ended almost every line in our programs with a semicolon. There’s no semicolon here, though. Why not?

The answer to this question is:

The return value of a function is the value of its final expression.

We haven’t talked about expressions yet, so this definition doesn’t help a lot. Let’s go over that now.

Statements and Expressions

Rust is an ‘expression oriented’ language. This means that most language constructs are an expression. But what are expressions? Expressions are bits of code that evaluate to a value. Consider some math operations, like this:

5 + 6

We can evaluate this expression, and come up with a value: 11. In Rust, most bits of code are expressions. For example, calling a function is an expression:

foo(5)

The value is equal to whatever the return value of foo() is.

So why does this matter? Well, not everything is an expression. Some things are ‘statements’. Statements are like expressions, but do not evaluate to a value. We’ve already seen two kinds of statements: let statements, and fn declarations.

Because let is a statement, not an expression, you can’t assign it to another binding. Here’s an example that doesn’t work:

fn main() {
    let x = (let y = 6);
}

If we try to run this program, we’ll get an error:

$ cargo run
   Compiling functions v0.1.0 (file:///home/steve/tmp/functions)
src/main.rs:2:14: 2:17 error: expected identifier, found keyword `let`
src/main.rs:2     let x = (let y = 6);
                           ^~~
src/main.rs:2:18: 2:19 error: expected one of `!`, `)`, `,`, `.`, `::`, `{`, or an operator, found `y`
src/main.rs:2     let x = (let y = 6);
                               ^
Could not compile `functions`.

We also cannot somehow assign a fn declaration to a binding, either.

So what’s this have to do with return values? Well, {}, a ‘block’ that we used earlier to create new scopes, is an expression. Let’s take a closer look at {}. It looks like this:

{
    STATEMENT*
    EXPRESSION
}

The * there means ‘zero or more’, so we can have any number of statements followed by an expression. Since blocks are expressions themselves, we can nest blocks inside of blocks. And since they return a value, we can use them in let statements:

fn main() {
    let x = 5;

    let y = {
        let z = 1;
        
        x + z + 5
    };

    println!("The value of y is: {}", y);
}

Let’s try running this program:

   Compiling functions v0.1.0 (file:///home/steve/tmp/functions)
     Running `target/debug/functions`
The value of y is: 11

We’re now using a block to give us a value for y:

let y = {

};

Since the block can contain statements, we create a new variable binding, z, and give it a value. We then do some math for the final expression of the block:

{
    let z = 1;

    x + z + 5
}

5 + 1 + 5 is 11, and so the value of the entire block is 11. This gets substituted into our let statement for y:

let y = 11;

Hence our output saying y is 11.

Where else do we use blocks? As the body of functions! They’re very similar:

fn main() {
    let x = 5;

    let y = {
        x + 1
    };

    println!("The value of y is: {}", y);

    let y = plus_one(x);

    println!("The value of y is: {}", y);
}

fn plus_one(x: i32) -> i32 {
    x + 1
}

Running this gives:

$ cargo run
   Compiling functions v0.1.0 (file:///home/steve/tmp/functions)
     Running `target/debug/functions`
The value of y is: 6
The value of y is: 6

In both cases, we use a block to produce a value. In the first case, it’s assigning with let:

let y = {

In the second, it’s the return value of the function:

fn plus_one(x: i32) -> i32 {

Expression statements

There’s one more detail about expressions and statements: a semicolon takes any expression, and turns it into a statement. Let’s accidentally cause an error with plus_one():

fn main() {
    let x = plus_one(5);

    println!("The value of x is: {}", x);
}

fn plus_one(x: i32) -> i32 {
    x + 1;
}

Instead of an expression, x + 1, we’ve now turned it into a statement, x + 1;.

Running this gives an error:

$ cargo run
   Compiling functions v0.1.0 (file:///home/steve/tmp/functions)
src/main.rs:7:1: 9:2 error: not all control paths return a value [E0269]
src/main.rs:7 fn plus_one(x: i32) -> i32 {
src/main.rs:8     x + 1;
src/main.rs:9 }
src/main.rs:7:1: 9:2 help: run `rustc --explain E0269` to see a detailed explanation
src/main.rs:8:10: 8:11 help: consider removing this semicolon:
src/main.rs:8     x + 1;
                       ^
error: aborting due to previous error
Could not compile `functions`.

Rust has our back here: it even suggests removing the semicolon, which fixes the error. But the main error message is the core of the issue: statements don’t evaluate to a value, yet we want to return an i32.

In practice, Rust programmers don’t often think about these rules at this level. Usually, you have a semicolon at the end of most lines, and maybe not at the end of blocks. When looking at the rules, they can seem a bit strange, but in practice, it works well.

Multiple return values

Functions cannot directly return multiple values. There’s a trick, however. Remember the ()s we used when showing off complex bindings?

fn main() {
    let (x, y) = (5, 6);
}

They form something called a ‘tuple’, one of Rust’s basic types. A tuple is an anonymous collection of elements. But since a tuple is a singular thing, we can use it as a way to return multiple values from functions:

fn main() {
    let (x, y) = two_numbers();

    println!("The value of x is: {}", x);
    println!("The value of y is: {}", y);
}

fn two_numbers() -> (i32, i32) {
    (5, 6)
}

Running this will show us the values:

$ cargo run
   Compiling functions v0.1.0 (file:///home/steve/tmp/functions)
     Running `target/debug/functions`
The value of x is: 5
The value of y is: 6

There are two interesting changes here: assigning the return value of two_numbers() to x and y, and the declaration of two_numbers() itself.

Let’s look at the declaration first:

fn two_numbers() -> (i32, i32) {
    (5, 6)
}

The (i32, i32) should look familiar. We saw it in let bindings earlier:

let (x, y): (i32, i32) = (5, 6);

The (i32, i32) syntax says “a tuple with two i32s in it.” The (5, 6) syntax creates a new one, with 5 and 6.

This tuple is then returned, and assigned to x and y:

let (x, y) = two_numbers();

See how all these bits fit together?

We call this behavior of let ‘destructuring’, because it takes the structure of the expression that comes after the = and takes it apart.

Primitive Types

We’ve seen that every value in Rust has a type of some kind. There are a number of types which are built into the language itself. We call these types ‘primitive’ types, since you can’t re-create them yourself. There are, of course, many non-primitive types provided by the standard library as well.

Remember, you can rely on type inference to figure out the type of a binding, or you can annotate it explicitly:

fn main() {
    let x: i32 = 5;
}

Integers

You’ve already seen one primitive type: i32. There are a number of built-in number types in Rust.

Here’s a chart of Rust’s integer types:

| | signed | unsigned | |--------|--------|----------| | 8-bit | i8 | u8 | | 16-bit | i16 | u16 | | 32-bit | i32 | u32 | | 64-bit | i64 | u64 | | arch | isize | usize |

We have both signed and unsigned variants of numbers, and each variant has an explicit size. Unsigned numbers are always positive, and signed numbers can be positive or negative. (Think ‘plus sign’ or ‘minus sign’: that’s a signed number.) Signed numbers are stored using ‘two’s compliment’ representation.

Finally, isize and usize are different sizes based on the kind of computer your program is running on. If you are on a 64-bit architecture, they are 64 bits, and if you’re on a 32-bit one, they’re 32 bits.

So how do you choose from all these options? Well, if you really don’t know, the defualts are a good choice: integer types default to i32. The primary use case for isize/usize is when indexing some sort of collection. We’ll talk more about our first collection, arrays, in just a moment.

Floating-point numbers

Rust also has two primitive floating-point numbers: f32 and f64. They are 32 bits and 64 bits in size, respectively. The default is f64.

fn main() {
    let x = 2.0; // f64

    let y: f32 = 3.0; // f32
}

Floating-point numbers are represented according to the IEEE-754 standard. f32 is a single-precision float, f64 is double-precision.

Tuples

The other type we’ve seen previously is the tuple type. Tuples have an ‘arity’, or size. We might say “that’s a 3-tuple” or “that’s a 5-tuple.”

Each position in a tuple has a distinct type:

fn main() {
    let x: (i32, f64, u8) = (500, 6.4, 1);
}

Tuples are used sparingly in Rust code. This is because the elements of a tuple are anonymous, which can make code hard to read.

Tuple indexing

To access an element of a tuple, we use a . followed by the index we want to access:

fn main() {
    let x: (i32, f64, u8) = (500, 6.4, 1);

    let five_hundred = x.0;
    let six_point_four = x.1;
    let one = x.2;
}

As you can see, the first index is 0.

Single-element tuples

There’s one last trick with tuples: (5) is actually ambiguous: is it a tuple, or is it a 5 in parethesis? If you need to disambiguate, use a comma:

fn main() {
    let x = (5); // x is an i32, no tuple. Think of it like (5 + 1) without the + 1, they’re for grouping.

    let x = (5,); // x is a (i32), a tuple with one element.
}

Functions

There’s one more type that we’ve been using, but you haven’t seen written explicitly. Functions! Functions also have a type, and yes, you can even have variables which hold functions! Here’s an example:

fn plus_one(x: i32) -> i32 {
    x + 1
}

fn main() {
    let f = plus_one;
    let g: fn(i32) -> i32 = plus_one; // with an explicit type annotation

    let five = f(4);
}

As you can see, the type is very similar to the declaration. Here, let’s put them side by side:

fn(i32) -> i32 // type
fn plus_one(x: i32) -> i32 { // declaration

If we take the declaration, and drop the name...

fn(i32) -> i32 // type
fn(x: i32) -> i32 {

And then drop the names of the arguments...

fn(i32) -> i32 // type
fn(i32) -> i32 {

It’s the same! Well, we need to drop that { as well.

Finally, if you’ll notice in that example, we can create a binding with a function in it:

fn main() {
    let f = plus_one;

    let five = f(4);
}

... and call it with ()s just like if we had used the original name.

Functions as arguments

So why not just use the original name? Well, we can pass functions as arguments to other functions! Check this out:

fn plus_one(x: i32) -> i32 {
    x + 1
}

fn plus_two(x: i32) -> i32 {
    x + 2
}

fn twice(x: i32, f: fn(i32) -> i32) -> i32 {
    let mut result = x;

    result = f(result);
    result = f(result);

    result 
}

fn main() {
    let x = 5;

    let y = twice(x, plus_one);
    let z = twice(x, plus_two);

    println!("The value of y is: {}", y);
    println!("The value of z is: {}", z);
}

If we compile and run this, we’ll get this output:

The value of y is: 7
The value of z is: 9

Let’s investigate in more detail.

fn twice(x: i32, f: fn(i32) -> i32) -> i32 {

This says “twice() is a function which takes two arguments. x is a thirty-two bit integer, and f is a function which takes an i32 and returns an i32.”

Inside of twice(), as you might imagine, we call the function f twice on x, and return the result.

let y = twice(x, plus_one);
let z = twice(x, plus_two);

The first time we call twice(), we pass plus_one() as an argument. And x is 5. So 5 + 1 + 1 == 7, hence our first line of output. The second time, we pass plus_two() instead. 5 + 2 + 2 is 9, and our second line checks out too.

Passing functions to functions is very, very powerful.

Booleans

Somewhat fundamental to all computing, Rust has a boolean type, bool, with two possible values:

fn main() {
    let t = true;
    let f: bool = false; // with explict type annotation
}

That’s really all there is to say about that!

Arrays

So far, we’ve only represented single values in a binding. Sometimes, though, it’s useful to have more than one value. These kinds of data structures are called ‘collections’, and arrays are the ones we’ll learn about first. Arrays look like this:

fn main() {
    let a = [1, 2, 3, 4, 5];
}

An array’s type consists of the type of the elements it contains, as well as the length:

fn main() {
    let a: [i32; 5] = [1, 2, 3, 4, 5];
}

An array is a single chunk of memory, allocated on the stack.

We can access elements of an array using indexing:

fn main() {
    let a = [1, 2, 3, 4, 5];

    let first = a[0];
    let second = a[1];
}

In this example, first will hold the value 1, and second will be bound to 2. Note that these values are copied out of the array; if the array changes, these bindings will not. Here’s an example, which also shows us how we can modify elements of the array:

fn main() {
    let mut a = [1, 2, 3, 4, 5];

    let first = a[0];
    
    a[0] = 7;

    println!("The value of first is: {}", first);
}

Running this example will show that first is still 1. If we didn’t want a copy, but instead wanted to refer to the first element, whatever its value was, we need a new concept. We’ll talk about ‘references’ in Section 4.

One last thing: now that we are modifying the array, a needs to be declared mut.

Arrays are our first real data structure, and so there’s a few other concepts that we haven’t covered in full yet. There are two: the panic! macro, and a new way of printing things: Debug.

Panic

We showed what happens when you access elements of an array, but what if we give an invalid index?

fn main() {
    let a = [1, 2, 3, 4, 5];

    let invalid = a[10];

    println!("The value of invalid is: {}", invalid);
}

If we run this example, we will get an error. Let’s re-use our functions project from before. Change your src/main.rs to look like the example, and run it:

$ cargo run
   Compiling functions v0.1.0 (file:///home/steve/tmp/functions)
     Running `target/debug/functions`
thread ‘<main>’ panicked at ‘index out of bounds: the len is 5 but the index is 10’, src/main.rs:4
Process didn’t exit successfully: `target/debug/functions` (exit code: 101)

It says that our thread panicked, and that our program didn’t exit successfully. There’s also a reason: we had a length of five, but an index of 10.

A ‘panic’ can also be induced manually, with the panic! macro:

fn main() {
    panic!("Oh no!");
}

When the panic! macro runs, it will cause a panic. When a Rust program panics, it starts a kind of controlled crash. The current thread of execution will stop entirely. As such, panics are reserved for serious, program-ending errors. They’re not a general error-handling mechanism.

So why did this code panic? Well, arrays know how many elements they hold. When we access an element via indexing, Rust will check that the index is less than the length. If it’s greater, it will panic, as something is very wrong. This is our first example of Rust’s safety principles in action. In many low-level languages, this kind of check is not done. If you have an incorrect index, invalid memory can be accessed. Rust protects us against this kind of error.

Steve’s note: this next bit might be our first ‘advanced’ section, on get()?

Debug

So far, we’ve been printing values using {}. If we try that with an array, though...

fn main() {
    let a = [1, 2, 3, 4, 5];

    println!("a is: {}", a);
}

... we will get an error:

$ cargo run
   Compiling functions v0.1.0 (file:///home/steve/tmp/functions)
src/main.rs:4:25: 4:26 error: the trait `core::fmt::Display` is not implemented for the type `[_; 5]` [E0277]
src/main.rs:4     println!(“a is {}”, a);
                                      ^
<std macros>:2:25: 2:56 note: in this expansion of format_args!
<std macros>:3:1: 3:54 note: in this expansion of print! (defined in <std macros>)
src/main.rs:4:5: 4:28 note: in this expansion of println! (defined in <std macros>)
src/main.rs:4:25: 4:26 help: run `rustc --explain E0277` to see a detailed explanation
src/main.rs:4:25: 4:26 note: `[_; 5]` cannot be formatted with the default formatter; try using `:?` instead if you are using a format string
src/main.rs:4:25: 4:26 note: required by `core::fmt::Display::fmt`
error: aborting due to previous error

Whew! The core of the error is this part: the trait core::fmt::Display is not implemented. We haven’t discussed traits yet, so this is bound to be confusing! Here’s all we need to know for now: println! can do many kinds of formatting. By default, {} implements a kind of formatting known as Display: output for end-users. The primitive types we’ve seen so far implement Display, as there’s only one way you’d show a 1 to a user. But with arrays, the output is less clear. Do you want commas or not? What about the []s?

Due to these questions, more complex types in the standard library do not implement Display formatting. There is another kind of formatting, Deubg, which is a bit different: output for programmers and debuggers. We can ask println! to use Debug formatting with :?:

fn main() {
    let a = [1, 2, 3, 4, 5];

    println!("a is {:?}", a);
}

This will work:

$ cargo run
   Compiling functions v0.1.0 (file:///home/steve/tmp/functions)
     Running `target/debug/functions`
a is [1, 2, 3, 4, 5]

You’ll see this repeated later, with other types. And we’ll cover traits fully later in the book, Section 9.

char

We’ve only worked with numbers so far, but what about letters? Rust’s most primitive alphabetic type is the char:

fn main() {
   let c = 'z'; 
   let z = 'ℤ'; 
}

Rust’s char represents a Unicode Scalar Value, which means that it can represent a lot more than just ASCII. “Character” isn’t really a concept in Unicode, however: your human intutition for what a ‘character’ is may not match up with a char. It also means that chars are four bytes each.

The single quotes are important: to define a literal single character, we use single quotes. If we used double quotes, we’d be defining a &str. Let’s talk about that next!

str

We can declare literal strings with "s. We’ve seen them already, with println!:

fn main() {
    println!("println! takes a literal string as an argument.");

    let s = "We can also create bindings to string literals.";

    let s: &str = "Here’s one with a type annotation.";
}

String literals are immutable, and of a fixed length. Rust has a second string type, String, that we’ll discuss in section 8.

&strs are UTF-8 encoded.

Comments

We strive to make our programs easy to understand, but sometimes, some extra explanation is warranted. We can leave notes in our source code that the compiler will ignore. These notes are called ‘comments’.

Here’s a comment:

// Hello, world.

Comments start with two slashes, and last until the end of the line. Larger comments will need more lines:

// So we’re doing something complicated here, long enough that we need
// multiple lines of comments to do it! Whew! Hopefully, this comment will
// explain what’s going on.

Comments can also go at the end of lines:

fn main() {
    let lucky_number = 7; // I’m feeling lucky today.
}

But you’ll more often see them above:

fn main() {
    // I’m feeling lucky today.
    let lucky_number = 7;
}

That’s all there is to it. Comments are not particularly complicated.

Documentation comments

However, Rust has another kind of comment: a documentation comment. These comments don’t affect the way that the code works, but they do work with Rust’s tools. More specifically, the rustdoc tool that comes with Rust reads documentation comments and produces HTML documentation from them.

Documentation comments use an extra slash:

/// The foo function doesn’t really do much.
fn foo() {
}

/// We also can use
/// multiple comments here too,
/// like we did before
fn bar() {
}

This comment would then be interpreted by rustdoc as documenting the thing that follows it: foo() and bar().

Because documentation comments have semantic meaning to rustdoc, the compiler will pay attention to the placement of your documentation comments. For example, a program with only this:

/// What am I documenting?

Will give a compiler error:

src/main.rs:1:1: 1:27 error: expected item after doc comment
src/main.rs:1 /// What am I documenting?
              ^~~~~~~~~~~~~~~~~~~~~~~~~~

Inner documentation comments

There is a secondary form of a documentation comment, an ‘inner’ documentation comment. Inner documentation comments look like this: //!. They are only really used to document modules, however, and so we will talk about them in the modules section.

if

Two roads diverged in a yellow wood, And sorry I could not travel both And be one traveler, long I stood And looked down one as far as I could To where it bent in the undergrowth;

  • Robert Frost, “The Road Not Taken”

One of the most primitive operations in computer programming is the ability to ‘branch’ between two different code paths. A program can look at a value, and then decide: should I follow this path, or should I take the other? There’s actually two different metaphors here: a tree, whose branches come from the same, single trunk. And a road, which splits off into two, each going in a different direction.

In Rust, there are a few ways to cause our code to branch. The most fundamental way is by using if. An if expression gives us two paths forward, and asks the question, “Which one should I take?”

Let’s make a new project to explore if. Navigate to your projects directory, and use Cargo to make a new project called branches:

$ cargo new --bin branches
$ cd branches

Here’s a sample program using if:

fn main() {
    let condition = true;

    if condition {
        println!("condition was true");
    } else {
        println!("condition was false");
    }
}   

Let's try running it:

$ cargo run
   Compiling branches v0.1.0 (file:///home/steve/tmp/branches)
     Running `target/debug/branches`
condition was true

We can change the value of condition:

    let condition = false;

And then run it again:

$ cargo run
   Compiling branches v0.1.0 (file:///home/steve/tmp/branches)
     Running `target/debug/branches`
condition was false

This is the very basic structure of if: if the condition is true, then execute some code. If it’s not true, then execute some other code, after else.

An else is not required:

fn main() {
    let condition = false;

    if condition {
        println!("condition was true");
    }
}

In this case, nothing is printed.

It’s also worth noting that condition here must be a bool. Let’s try an example with something else:

fn main() {
    let condition = 5;

    if condition {
        println!("condition was five");
    }
}

If we try to run this program, Rust will complain:

   Compiling branches v0.1.0 (file:///home/steve/tmp/branches)
src/main.rs:4:8: 4:17 error: mismatched types:
 expected `bool`,
    found `_`
(expected bool,
    found integral variable) [E0308]
src/main.rs:4     if condition {
                     ^~~~~~~~~
src/main.rs:4:8: 4:17 help: run `rustc --explain E0308` to see a detailed explanation
error: aborting due to previous error
Could not compile `branches`.

We expected a bool, but got an integer. Rust will not automatically try to convert non-boolean types to a boolean here. We must be explicit.

else if

We can make multiple decisions by combining if and else in another way:

fn main() {
    let number = 5;

    if number == 3 {
        println!("condition was 3");
    } else if number == 4 {
        println!("condition was 4");
    } else if number == 5 {
        println!("condition was 5");
    } else {
        println!("condition was something else");
    }
}

Let's try running it:

$ cargo run
   Compiling branches v0.1.0 (file:///home/steve/tmp/branches)
     Running `target/debug/branches`
condition was 5

When this program executes, it will check each if in turn, and execute the first body for which the condition holds true.

Using a single else if can be okay, but if you find yourself with more than one, you may want to refactor your code. Rust has a more powerful branching construct called match for these cases. We'll cover it later, when we talk about enums.

if as an expression

There’s one last detail we need to learn about if: it’s an expression. That means that we can use it on the right hand side of a let binding, for instance:

fn main() {
    let condition = true;

    let number = if condition {
        5
    } else {
        6
    };

    println!("The value of number is: {}", number);
}

Let’s run this:

$ cargo run
   Compiling branches v0.1.0 (file:///home/steve/tmp/branches)
     Running `target/debug/branches`
The value of number is: 5

Remember, blocks of code evaluate to the last expression in them. And numbers by themselves are also expressions. So in this case, the value of the whole if expression depends on which block of code executes.

There’s another small detail involved here: this means that if you use if in this way, both arms of the if must be the same type. This doesn’t work:

fn main() {
    let condition = true;

    let number = if condition {
        5
    } else {
        "six"
    };

    println!("The value of number is: {}", number);
}

If we try to run this, we’ll get an error:

   Compiling branches v0.1.0 (file:///home/steve/tmp/branches)
src/main.rs:4:18: 8:6 error: if and else have incompatible types:
 expected `_`,
    found `&‘static str`
(expected integral variable,
    found &-ptr) [E0308]
src/main.rs:4     let number = if condition {
src/main.rs:5         5
src/main.rs:6     } else {
src/main.rs:7         "six"
src/main.rs:8     };
src/main.rs:4:18: 8:6 help: run `rustc --explain E0308` to see a detailed explanation
error: aborting due to previous error
Could not compile `branches`.

if and else have incompatible types. This can’t work. This also means that you almost certainly need an else when using if in this way. If you don’t, what would the value be if the condition was false?

Loops

It’s often quite useful to be able to execute a block of code more than one time. For this, we have several constructs, called ‘loops’.

To try out loops, let’s make a new project. Navigate to your projects folder and use Cargo to make a new one:

$ cargo new --bin loops
$ cd loops

There are three kinds of loops in Rust: loop, while, and for. Let’s dig in.

loop

The loop keyword is very straightforward: it executes a block of code over and over and over and over and over and over forever. Change your src/main.rs file to look like this:

fn main() {
    loop {
        println!("again!");
    }
}

If we run this program, we’ll see ‘again!’ printed over and over again. So how does our program end? It doesn’t, until we kill it. Most terminals support a keyboard shortcut, ‘control-c’, to stop a runaway program. Give it a try:

$ cargo run
   Compiling loops v0.1.0 (file:///home/steve/tmp/loops)
     Running `target/debug/loops`
again!
again!
again!
again!
^Cagain!

That ^C there is where I hit control-c.

That’s a lot of trouble though! Luckily, there’s a way to break an infinite loop.

Breaking out of a loop

The break keyword will allow us to quit looping. Try this version out:

fn main() {
    loop {
        println!("once!");
        break;
    }
}

If you run this program with cargo run, you’ll see that it only executes one time:

$ cargo run
   Compiling loops v0.1.0 (file:///home/steve/tmp/loops)
     Running `target/debug/loops`
once!

When a Rust program hits a break statement, it will exit the current loop.

while

What if we took loop, break, and if, and put them together? Something like this:

fn main() {
    let mut number = 3;

    loop {
        if number != 0 {
            println!("{}!", number);

            number = number - 1;
        } else {
            break;
        }

    }

    println!("LIFTOFF!!!");
}

If we run this, we’ll get some output:

   Compiling loops v0.1.0 (file:///home/steve/tmp/loops)
     Running `target/debug/loops`
3!
2!
1!
LIFTOFF!!!

The core of this example is in the combination of these three constructs:

    loop {
        if number != 0 {
            // do stuff
        } else {
            break;
        }

We want to loop, but only while some sort of condition is true. As soon as it isn't, we want to break out of the loop.

This pattern is so common that we have a language construct for it: while. Here's the same example, but using while instead:

fn main() {
    let mut number = 3;
    while number != 0  {
        println!("{}!", number);

        number = number - 1;
    }

    println!("LIFTOFF!!!");
}

This lets us get rid of a lot of nesting, and is more clear: while a condition holds, run this code.

for

We can use this while construct to loop over the elements of a collection, like an array:

fn main() {
    let a = [1, 2, 3, 4, 5];
    let mut index = 0;

    while index < 5 {
        println!("the value is is: {}", a[index]);

        index = index + 1;
    }
}

Running this will print out every element of the array:

$ cargo run
   Compiling loops v0.1.0 (file:///home/steve/tmp/loops)
     Running `target/debug/loops`
the value is: 1
the value is: 2
the value is: 3
the value is: 4
the value is: 5

Here, we're counting up instead of down: we start at zero, then loop until we hit the final index of our array.

This approach is error-prone, though. If we get the index length incorrect, we will end up causing a panic!. This is also slow, as the compiler needs to do that check on every element on every iteration through the loop.

Instead, we can use our last kind of loop: the for loop. It looks like this:

fn main() {
    let a = [1, 2, 3, 4, 5];
    let mut index = 0;
    
    for element in a.iter() {
        println!("the value is: {}", element);
    }
}

** NOTE: see https://github.com/rust-lang/rust/issues/25725#issuecomment-166365658, we may want to change this **

If we run this, we'll see the same output as the previous example.

** I'm going to leave it at this for now until we decide how we want to do it**

Ownership & borrowing

Ownership

This guide is one of three presenting Rust’s ownership system. This is one of Rust’s most unique and compelling features, with which Rust developers should become quite acquainted. Ownership is how Rust achieves its largest goal, memory safety. There are a few distinct concepts, each with its own chapter:

  • ownership, which you’re reading now
  • borrowing, and their associated feature ‘references’
  • lifetimes, an advanced concept of borrowing

These three chapters are related, and in order. You’ll need all three to fully understand the ownership system.

Meta

Before we get to the details, two important notes about the ownership system.

Rust has a focus on safety and speed. It accomplishes these goals through many ‘zero-cost abstractions’, which means that in Rust, abstractions cost as little as possible in order to make them work. The ownership system is a prime example of a zero-cost abstraction. All of the analysis we’ll talk about in this guide is done at compile time. You do not pay any run-time cost for any of these features.

However, this system does have a certain cost: learning curve. Many new users to Rust experience something we like to call ‘fighting with the borrow checker’, where the Rust compiler refuses to compile a program that the author thinks is valid. This often happens because the programmer’s mental model of how ownership should work doesn’t match the actual rules that Rust implements. You probably will experience similar things at first. There is good news, however: more experienced Rust developers report that once they work with the rules of the ownership system for a period of time, they fight the borrow checker less and less.

With that in mind, let’s learn about ownership.

Ownership

Variable bindings have a property in Rust: they ‘have ownership’ of what they’re bound to. This means that when a binding goes out of scope, Rust will free the bound resources. For example:

fn foo() {
    let v = vec![1, 2, 3];
}

When v comes into scope, a new [Vec<T>]vect is created. In this case, the vector also allocates space on the heap, for the three elements. When v goes out of scope at the end of foo(), Rust will clean up everything related to the vector, even the heap-allocated memory. This happens deterministically, at the end of the scope.

Move semantics

There’s some more subtlety here, though: Rust ensures that there is exactly one binding to any given resource. For example, if we have a vector, we can assign it to another binding:

let v = vec![1, 2, 3];

let v2 = v;

But, if we try to use v afterwards, we get an error:

let v = vec![1, 2, 3];

let v2 = v;

println!("v[0] is: {}", v[0]);

It looks like this:

error: use of moved value: `v`
println!("v[0] is: {}", v[0]);
                        ^

A similar thing happens if we define a function which takes ownership, and try to use something after we’ve passed it as an argument:

fn take(v: Vec<i32>) {
    // what happens here isn’t important.
}

let v = vec![1, 2, 3];

take(v);

println!("v[0] is: {}", v[0]);

Same error: ‘use of moved value’. When we transfer ownership to something else, we say that we’ve ‘moved’ the thing we refer to. You don’t need some sort of special annotation here, it’s the default thing that Rust does.

The details

The reason that we cannot use a binding after we’ve moved it is subtle, but important. When we write code like this:

let v = vec![1, 2, 3];

let v2 = v;

The first line allocates memory for the vector object, v, and for the data it contains. The vector object is stored on the stack and contains a pointer to the content ([1, 2, 3]) stored on the heap. When we move v to v2, it creates a copy of that pointer, for v2. Which means that there would be two pointers to the content of the vector on the heap. It would violate Rust’s safety guarantees by introducing a data race. Therefore, Rust forbids using v after we’ve done the move.

It’s also important to note that optimizations may remove the actual copy of the bytes on the stack, depending on circumstances. So it may not be as inefficient as it initially seems.

Copy types

We’ve established that when ownership is transferred to another binding, you cannot use the original binding. However, there’s a trait that changes this behavior, and it’s called Copy. We haven’t discussed traits yet, but for now, you can think of them as an annotation to a particular type that adds extra behavior. For example:

let v = 1;

let v2 = v;

println!("v is: {}", v);

In this case, v is an i32, which implements the Copy trait. This means that, just like a move, when we assign v to v2, a copy of the data is made. But, unlike a move, we can still use v afterward. This is because an i32 has no pointers to data somewhere else, copying it is a full copy.

All primitive types implement the Copy trait and their ownership is therefore not moved like one would assume, following the ´ownership rules´. To give an example, the two following snippets of code only compile because the i32 and bool types implement the Copy trait.

fn main() {
    let a = 5;

    let _y = double(a);
    println!("{}", a);
}

fn double(x: i32) -> i32 {
    x * 2
}
fn main() {
    let a = true;

    let _y = change_truth(a);
    println!("{}", a);
}

fn change_truth(x: bool) -> bool {
    !x
}

If we had used types that do not implement the Copy trait, we would have gotten a compile error because we tried to use a moved value.

error: use of moved value: `a`
println!("{}", a);
               ^

We will discuss how to make your own types Copy in the traits section.

More than ownership

Of course, if we had to hand ownership back with every function we wrote:

fn foo(v: Vec<i32>) -> Vec<i32> {
    // do stuff with v

    // hand back ownership
    v
}

This would get very tedious. It gets worse the more things we want to take ownership of:

fn foo(v1: Vec<i32>, v2: Vec<i32>) -> (Vec<i32>, Vec<i32>, i32) {
    // do stuff with v1 and v2

    // hand back ownership, and the result of our function
    (v1, v2, 42)
}

let v1 = vec![1, 2, 3];
let v2 = vec![1, 2, 3];

let (v1, v2, answer) = foo(v1, v2);

Ugh! The return type, return line, and calling the function gets way more complicated.

Luckily, Rust offers a feature, borrowing, which helps us solve this problem. It’s the topic of the next section!

References and Borrowing

Slices

We saw how to use indexing to get a single element out of an array. But we can also use indexing to get a reference to multiple elements:

fn main() {
    let a = [1, 2, 3, 4, 5];

    let s = &a[0..2];

    println!("The value of s is: {:?}", s);
}

Let’s try running it:

$ cargo run
   Compiling functions v0.1.0 (file:///home/steve/tmp/functions)
     Running `target/debug/functions`
The value of s is: [1, 2]

This guide is two of three presenting Rust’s ownership system. This is one of Rust’s most unique and compelling features, with which Rust developers should become quite acquainted. Ownership is how Rust achieves its largest goal, memory safety. There are a few distinct concepts, each with its own chapter:

  • ownership, the key concept
  • borrowing, which you’re reading now
  • lifetimes, an advanced concept of borrowing

These three chapters are related, and in order. You’ll need all three to fully understand the ownership system.

Meta

Before we get to the details, two important notes about the ownership system.

Rust has a focus on safety and speed. It accomplishes these goals through many ‘zero-cost abstractions’, which means that in Rust, abstractions cost as little as possible in order to make them work. The ownership system is a prime example of a zero cost abstraction. All of the analysis we’ll talk about in this guide is done at compile time. You do not pay any run-time cost for any of these features.

However, this system does have a certain cost: learning curve. Many new users to Rust experience something we like to call ‘fighting with the borrow checker’, where the Rust compiler refuses to compile a program that the author thinks is valid. This often happens because the programmer’s mental model of how ownership should work doesn’t match the actual rules that Rust implements. You probably will experience similar things at first. There is good news, however: more experienced Rust developers report that once they work with the rules of the ownership system for a period of time, they fight the borrow checker less and less.

With that in mind, let’s learn about borrowing.

Borrowing

At the end of the ownership section, we had a nasty function that looked like this:

fn foo(v1: Vec<i32>, v2: Vec<i32>) -> (Vec<i32>, Vec<i32>, i32) {
    // do stuff with v1 and v2

    // hand back ownership, and the result of our function
    (v1, v2, 42)
}

let v1 = vec![1, 2, 3];
let v2 = vec![1, 2, 3];

let (v1, v2, answer) = foo(v1, v2);

This is not idiomatic Rust, however, as it doesn’t take advantage of borrowing. Here’s the first step:

fn foo(v1: &Vec<i32>, v2: &Vec<i32>) -> i32 {
    // do stuff with v1 and v2

    // return the answer
    42
}

let v1 = vec![1, 2, 3];
let v2 = vec![1, 2, 3];

let answer = foo(&v1, &v2);

// we can use v1 and v2 here!

Instead of taking Vec<i32>s as our arguments, we take a reference: &Vec<i32>. And instead of passing v1 and v2 directly, we pass &v1 and &v2. We call the &T type a ‘reference’, and rather than owning the resource, it borrows ownership. A binding that borrows something does not deallocate the resource when it goes out of scope. This means that after the call to foo(), we can use our original bindings again.

References are immutable, just like bindings. This means that inside of foo(), the vectors can’t be changed at all:

fn foo(v: &Vec<i32>) {
     v.push(5);
}

let v = vec![];

foo(&v);

errors with:

error: cannot borrow immutable borrowed content `*v` as mutable
v.push(5);
^

Pushing a value mutates the vector, and so we aren’t allowed to do it.

&mut references

There’s a second kind of reference: &mut T. A ‘mutable reference’ allows you to mutate the resource you’re borrowing. For example:

let mut x = 5;
{
    let y = &mut x;
    *y += 1;
}
println!("{}", x);

This will print 6. We make y a mutable reference to x, then add one to the thing y points at. You’ll notice that x had to be marked mut as well. If it wasn’t, we couldn’t take a mutable borrow to an immutable value.

You'll also notice we added an asterisk (*) in front of y, making it *y, this is because y is an &mut reference. You'll also need to use them for accessing the contents of a reference as well.

Otherwise, &mut references are just like references. There is a large difference between the two, and how they interact, though. You can tell something is fishy in the above example, because we need that extra scope, with the { and }. If we remove them, we get an error:

error: cannot borrow `x` as immutable because it is also borrowed as mutable
    println!("{}", x);
                   ^
note: previous borrow of `x` occurs here; the mutable borrow prevents
subsequent moves, borrows, or modification of `x` until the borrow ends
        let y = &mut x;
                     ^
note: previous borrow ends here
fn main() {

}
^

As it turns out, there are rules.

The Rules

Here’s the rules about borrowing in Rust:

First, any borrow must last for a scope no greater than that of the owner. Second, you may have one or the other of these two kinds of borrows, but not both at the same time:

  • one or more references (&T) to a resource,
  • exactly one mutable reference (&mut T).

You may notice that this is very similar, though not exactly the same as, to the definition of a data race:

There is a ‘data race’ when two or more pointers access the same memory location at the same time, where at least one of them is writing, and the operations are not synchronized.

With references, you may have as many as you’d like, since none of them are writing. However, as we can only have one &mut at a time, it is impossible to have a data race. This is how Rust prevents data races at compile time: we’ll get errors if we break the rules.

With this in mind, let’s consider our example again.

Thinking in scopes

Here’s the code:

let mut x = 5;
let y = &mut x;

*y += 1;

println!("{}", x);

This code gives us this error:

error: cannot borrow `x` as immutable because it is also borrowed as mutable
    println!("{}", x);
                   ^

This is because we’ve violated the rules: we have a &mut T pointing to x, and so we aren’t allowed to create any &Ts. One or the other. The note hints at how to think about this problem:

note: previous borrow ends here
fn main() {

}
^

In other words, the mutable borrow is held through the rest of our example. What we want is for the mutable borrow to end before we try to call println! and make an immutable borrow. In Rust, borrowing is tied to the scope that the borrow is valid for. And our scopes look like this:

let mut x = 5;

let y = &mut x;    // -+ &mut borrow of x starts here
                   //  |
*y += 1;           //  |
                   //  |
println!("{}", x); // -+ - try to borrow x here
                   // -+ &mut borrow of x ends here

The scopes conflict: we can’t make an &x while y is in scope.

So when we add the curly braces:

let mut x = 5;

{
    let y = &mut x; // -+ &mut borrow starts here
    *y += 1;        //  |
}                   // -+ ... and ends here

println!("{}", x);  // <- try to borrow x here

There’s no problem. Our mutable borrow goes out of scope before we create an immutable one. But scope is the key to seeing how long a borrow lasts for.

Issues borrowing prevents

Why have these restrictive rules? Well, as we noted, these rules prevent data races. What kinds of issues do data races cause? Here’s a few.

Iterator invalidation

One example is ‘iterator invalidation’, which happens when you try to mutate a collection that you’re iterating over. Rust’s borrow checker prevents this from happening:

let mut v = vec![1, 2, 3];

for i in &v {
    println!("{}", i);
}

This prints out one through three. As we iterate through the vectors, we’re only given references to the elements. And v is itself borrowed as immutable, which means we can’t change it while we’re iterating:

let mut v = vec![1, 2, 3];

for i in &v {
    println!("{}", i);
    v.push(34);
}

Here’s the error:

error: cannot borrow `v` as mutable because it is also borrowed as immutable
    v.push(34);
    ^
note: previous borrow of `v` occurs here; the immutable borrow prevents
subsequent moves or mutable borrows of `v` until the borrow ends
for i in &v {
          ^
note: previous borrow ends here
for i in &v {
    println!(“{}”, i);
    v.push(34);
}
^

We can’t modify v because it’s borrowed by the loop.

use after free

References must not live longer than the resource they refer to. Rust will check the scopes of your references to ensure that this is true.

If Rust didn’t check this property, we could accidentally use a reference which was invalid. For example:

let y: &i32;
{
    let x = 5;
    y = &x;
}

println!("{}", y);

We get this error:

error: `x` does not live long enough
    y = &x;
         ^
note: reference must be valid for the block suffix following statement 0 at
2:16...
let y: &i32;
{
    let x = 5;
    y = &x;
}

note: ...but borrowed value is only valid for the block suffix following
statement 0 at 4:18
    let x = 5;
    y = &x;
}

In other words, y is only valid for the scope where x exists. As soon as x goes away, it becomes invalid to refer to it. As such, the error says that the borrow ‘doesn’t live long enough’ because it’s not valid for the right amount of time.

The same problem occurs when the reference is declared before the variable it refers to. This is because resources within the same scope are freed in the opposite order they were declared:

let y: &i32;
let x = 5;
y = &x;

println!("{}", y);

We get this error:

error: `x` does not live long enough
y = &x;
     ^
note: reference must be valid for the block suffix following statement 0 at
2:16...
    let y: &i32;
    let x = 5;
    y = &x;

    println!("{}", y);
}

note: ...but borrowed value is only valid for the block suffix following
statement 1 at 3:14
    let x = 5;
    y = &x;

    println!("{}", y);
}

In the above example, y is declared before x, meaning that y lives longer than x, which is not allowed.

Lifetimes

This guide is three of three presenting Rust’s ownership system. This is one of Rust’s most unique and compelling features, with which Rust developers should become quite acquainted. Ownership is how Rust achieves its largest goal, memory safety. There are a few distinct concepts, each with its own chapter:

  • ownership, the key concept
  • borrowing, and their associated feature ‘references’
  • lifetimes, which you’re reading now

These three chapters are related, and in order. You’ll need all three to fully understand the ownership system.

Meta

Before we get to the details, two important notes about the ownership system.

Rust has a focus on safety and speed. It accomplishes these goals through many ‘zero-cost abstractions’, which means that in Rust, abstractions cost as little as possible in order to make them work. The ownership system is a prime example of a zero-cost abstraction. All of the analysis we’ll talk about in this guide is done at compile time. You do not pay any run-time cost for any of these features.

However, this system does have a certain cost: learning curve. Many new users to Rust experience something we like to call ‘fighting with the borrow checker’, where the Rust compiler refuses to compile a program that the author thinks is valid. This often happens because the programmer’s mental model of how ownership should work doesn’t match the actual rules that Rust implements. You probably will experience similar things at first. There is good news, however: more experienced Rust developers report that once they work with the rules of the ownership system for a period of time, they fight the borrow checker less and less.

With that in mind, let’s learn about lifetimes.

Lifetimes

Lending out a reference to a resource that someone else owns can be complicated. For example, imagine this set of operations:

  1. I acquire a handle to some kind of resource.
  2. I lend you a reference to the resource.
  3. I decide I’m done with the resource, and deallocate it, while you still have your reference.
  4. You decide to use the resource.

Uh oh! Your reference is pointing to an invalid resource. This is called a dangling pointer or ‘use after free’, when the resource is memory.

To fix this, we have to make sure that step four never happens after step three. The ownership system in Rust does this through a concept called lifetimes, which describe the scope that a reference is valid for.

When we have a function that takes a reference by argument, we can be implicit or explicit about the lifetime of the reference:

// implicit
fn foo(x: &i32) {
}

// explicit
fn bar<'a>(x: &'a i32) {
}

The 'a reads ‘the lifetime a’. Technically, every reference has some lifetime associated with it, but the compiler lets you elide (i.e. omit, see "Lifetime Elision" below) them in common cases. Before we get to that, though, let’s break the explicit example down:

fn bar<'a>(...)

We previously talked a little about function syntax, but we didn’t discuss the <>s after a function’s name. A function can have ‘generic parameters’ between the <>s, of which lifetimes are one kind. We’ll discuss other kinds of generics later in the book, but for now, let’s just focus on the lifetimes aspect.

We use <> to declare our lifetimes. This says that bar has one lifetime, 'a. If we had two reference parameters, it would look like this:

fn bar<'a, 'b>(...)

Then in our parameter list, we use the lifetimes we’ve named:

...(x: &'a i32)

If we wanted an &mut reference, we’d do this:

...(x: &'a mut i32)

If you compare &mut i32 to &'a mut i32, they’re the same, it’s just that the lifetime 'a has snuck in between the & and the mut i32. We read &mut i32 as ‘a mutable reference to an i32’ and &'a mut i32 as ‘a mutable reference to an i32 with the lifetime 'a’.

In structs

You’ll also need explicit lifetimes when working with [struct]structss that contain references:

struct Foo<'a> {
    x: &'a i32,
}

fn main() {
    let y = &5; // this is the same as `let _y = 5; let y = &_y;`
    let f = Foo { x: y };

    println!("{}", f.x);
}

As you can see, structs can also have lifetimes. In a similar way to functions,

struct Foo<'a> {
# x: &'a i32,
# }

declares a lifetime, and

# struct Foo<'a> {
x: &'a i32,
# }

uses it. So why do we need a lifetime here? We need to ensure that any reference to a Foo cannot outlive the reference to an i32 it contains.

impl blocks

Let’s implement a method on Foo:

struct Foo<'a> {
    x: &'a i32,
}

impl<'a> Foo<'a> {
    fn x(&self) -> &'a i32 { self.x }
}

fn main() {
    let y = &5; // this is the same as `let _y = 5; let y = &_y;`
    let f = Foo { x: y };

    println!("x is: {}", f.x());
}

As you can see, we need to declare a lifetime for Foo in the impl line. We repeat 'a twice, just like on functions: impl<'a> defines a lifetime 'a, and Foo<'a> uses it.

Multiple lifetimes

If you have multiple references, you can use the same lifetime multiple times:

fn x_or_y<'a>(x: &'a str, y: &'a str) -> &'a str {
#    x
# }

This says that x and y both are alive for the same scope, and that the return value is also alive for that scope. If you wanted x and y to have different lifetimes, you can use multiple lifetime parameters:

fn x_or_y<'a, 'b>(x: &'a str, y: &'b str) -> &'a str {
#    x
# }

In this example, x and y have different valid scopes, but the return value has the same lifetime as x.

Thinking in scopes

A way to think about lifetimes is to visualize the scope that a reference is valid for. For example:

fn main() {
    let y = &5;     // -+ y goes into scope
                    //  |
    // stuff        //  |
                    //  |
}                   // -+ y goes out of scope

Adding in our Foo:

struct Foo<'a> {
    x: &'a i32,
}

fn main() {
    let y = &5;           // -+ y goes into scope
    let f = Foo { x: y }; // -+ f goes into scope
    // stuff              //  |
                          //  |
}                         // -+ f and y go out of scope

Our f lives within the scope of y, so everything works. What if it didn’t? This code won’t work:

struct Foo<'a> {
    x: &'a i32,
}

fn main() {
    let x;                    // -+ x goes into scope
                              //  |
    {                         //  |
        let y = &5;           // ---+ y goes into scope
        let f = Foo { x: y }; // ---+ f goes into scope
        x = &f.x;             //  | | error here
    }                         // ---+ f and y go out of scope
                              //  |
    println!("{}", x);        //  |
}                             // -+ x goes out of scope

Whew! As you can see here, the scopes of f and y are smaller than the scope of x. But when we do x = &f.x, we make x a reference to something that’s about to go out of scope.

Named lifetimes are a way of giving these scopes a name. Giving something a name is the first step towards being able to talk about it.

'static

The lifetime named ‘static’ is a special lifetime. It signals that something has the lifetime of the entire program. Most Rust programmers first come across 'static when dealing with strings:

let x: &'static str = "Hello, world.";

String literals have the type &'static str because the reference is always alive: they are baked into the data segment of the final binary. Another example are globals:

static FOO: i32 = 5;
let x: &'static i32 = &FOO;

This adds an i32 to the data segment of the binary, and x is a reference to it.

Lifetime Elision

Rust supports powerful local type inference in function bodies, but it’s forbidden in item signatures to allow reasoning about the types based on the item signature alone. However, for ergonomic reasons a very restricted secondary inference algorithm called “lifetime elision” applies in function signatures. It infers only based on the signature components themselves and not based on the body of the function, only infers lifetime parameters, and does this with only three easily memorizable and unambiguous rules. This makes lifetime elision a shorthand for writing an item signature, while not hiding away the actual types involved as full local inference would if applied to it.

When talking about lifetime elision, we use the term input lifetime and output lifetime. An input lifetime is a lifetime associated with a parameter of a function, and an output lifetime is a lifetime associated with the return value of a function. For example, this function has an input lifetime:

fn foo<'a>(bar: &'a str)

This one has an output lifetime:

fn foo<'a>() -> &'a str

This one has a lifetime in both positions:

fn foo<'a>(bar: &'a str) -> &'a str

Here are the three rules:

  • Each elided lifetime in a function’s arguments becomes a distinct lifetime parameter.

  • If there is exactly one input lifetime, elided or not, that lifetime is assigned to all elided lifetimes in the return values of that function.

  • If there are multiple input lifetimes, but one of them is &self or &mut self, the lifetime of self is assigned to all elided output lifetimes.

Otherwise, it is an error to elide an output lifetime.

Examples

Here are some examples of functions with elided lifetimes. We’ve paired each example of an elided lifetime with its expanded form.

fn print(s: &str); // elided
fn print<'a>(s: &'a str); // expanded

fn debug(lvl: u32, s: &str); // elided
fn debug<'a>(lvl: u32, s: &'a str); // expanded

// In the preceding example, `lvl` doesn’t need a lifetime because it’s not a
// reference (`&`). Only things relating to references (such as a `struct`
// which contains a reference) need lifetimes.

fn substr(s: &str, until: u32) -> &str; // elided
fn substr<'a>(s: &'a str, until: u32) -> &'a str; // expanded

fn get_str() -> &str; // ILLEGAL, no inputs

fn frob(s: &str, t: &str) -> &str; // ILLEGAL, two inputs
fn frob<'a, 'b>(s: &'a str, t: &'b str) -> &str; // Expanded: Output lifetime is ambiguous

fn get_mut(&mut self) -> &mut T; // elided
fn get_mut<'a>(&'a mut self) -> &'a mut T; // expanded

fn args<T:ToCStr>(&mut self, args: &[T]) -> &mut Command; // elided
fn args<'a, 'b, T:ToCStr>(&'a mut self, args: &'b [T]) -> &'a mut Command; // expanded

fn new(buf: &mut [u8]) -> BufWriter; // elided
fn new<'a>(buf: &'a mut [u8]) -> BufWriter<'a>; // expanded

Basic Data Types

Structs

structs are a way of creating more complex data types. For example, if we were doing calculations involving coordinates in 2D space, we would need both an x and a y value:

let origin_x = 0;
let origin_y = 0;

A struct lets us combine these two into a single, unified datatype with x and y as field labels:

struct Point {
    x: i32,
    y: i32,
}

fn main() {
    let origin = Point { x: 0, y: 0 }; // origin: Point

    println!("The origin is at ({}, {})", origin.x, origin.y);
}

There’s a lot going on here, so let’s break it down. We declare a struct with the struct keyword, and then with a name. By convention, structs begin with a capital letter and are camel cased: PointInSpace, not Point_In_Space.

We can create an instance of our struct via let, as usual, but we use a key: value style syntax to set each field. The order doesn’t need to be the same as in the original declaration.

Finally, because fields have names, we can access them through dot notation: origin.x.

The values in structs are immutable by default, like other bindings in Rust. Use mut to make them mutable:

struct Point {
    x: i32,
    y: i32,
}

fn main() {
    let mut point = Point { x: 0, y: 0 };

    point.x = 5;

    println!("The point is at ({}, {})", point.x, point.y);
}

This will print The point is at (5, 0).

Rust does not support field mutability at the language level, so you cannot write something like this:

struct Point {
    mut x: i32,
    y: i32,
}

Mutability is a property of the binding, not of the structure itself. If you’re used to field-level mutability, this may seem strange at first, but it significantly simplifies things. It even lets you make things mutable on a temporary basis:

struct Point {
    x: i32,
    y: i32,
}

fn main() {
    let mut point = Point { x: 0, y: 0 };

    point.x = 5;

    let point = point; // now immutable

    point.y = 6; // this causes an error
}

Update syntax

A struct can include .. to indicate that you want to use a copy of some other struct for some of the values. For example:

struct Point3d {
    x: i32,
    y: i32,
    z: i32,
}

let mut point = Point3d { x: 0, y: 0, z: 0 };
point = Point3d { y: 1, .. point };

This gives point a new y, but keeps the old x and z values. It doesn’t have to be the same struct either, you can use this syntax when making new ones, and it will copy the values you don’t specify:

# struct Point3d {
#     x: i32,
#     y: i32,
#     z: i32,
# }
let origin = Point3d { x: 0, y: 0, z: 0 };
let point = Point3d { z: 1, x: 2, .. origin };

Tuple structs

Rust has another data type that’s like a hybrid between a tuple and a struct, called a ‘tuple struct’. Tuple structs have a name, but their fields don't. They are declared with the struct keyword, and then with a name followed by a tuple:

struct Color(i32, i32, i32);
struct Point(i32, i32, i32);

let black = Color(0, 0, 0);
let origin = Point(0, 0, 0);

Here, black and origin are not equal, even though they contain the same values.

It is almost always better to use a struct than a tuple struct. We would write Color and Point like this instead:

struct Color {
    red: i32,
    blue: i32,
    green: i32,
}

struct Point {
    x: i32,
    y: i32,
    z: i32,
}

Good names are important, and while values in a tuple struct can be referenced with dot notation as well, a struct gives us actual names, rather than positions.

There is one case when a tuple struct is very useful, though, and that is when it has only one element. We call this the ‘newtype’ pattern, because it allows you to create a new type that is distinct from its contained value and also expresses its own semantic meaning:

struct Inches(i32);

let length = Inches(10);

let Inches(integer_length) = length;
println!("length is {} inches", integer_length);

As you can see here, you can extract the inner integer type through a destructuring let, just as with regular tuples. In this case, the let Inches(integer_length) assigns 10 to integer_length.

Unit-like structs

You can define a struct with no members at all:

struct Electron;

let x = Electron;

Such a struct is called ‘unit-like’ because it resembles the empty tuple, (), sometimes called ‘unit’. Like a tuple struct, it defines a new type.

This is rarely useful on its own (although sometimes it can serve as a marker type), but in combination with other features, it can become useful. For instance, a library may ask you to create a structure that implements a certain trait to handle events. If you don’t have any data you need to store in the structure, you can just create a unit-like struct.

Enums

An enum in Rust is a type that represents data that is one of several possible variants. Each variant in the enum can optionally have data associated with it:

enum Message {
    Quit,
    ChangeColor(i32, i32, i32),
    Move { x: i32, y: i32 },
    Write(String),
}

The syntax for defining variants resembles the syntaxes used to define structs: you can have variants with no data (like unit-like structs), variants with named data, and variants with unnamed data (like tuple structs). Unlike separate struct definitions, however, an enum is a single type. A value of the enum can match any of the variants. For this reason, an enum is sometimes called a ‘sum type’: the set of possible values of the enum is the sum of the sets of possible values for each variant.

We use the :: syntax to use the name of each variant: they’re scoped by the name of the enum itself. This allows both of these to work:

# enum Message {
#     Move { x: i32, y: i32 },
# }
let x: Message = Message::Move { x: 3, y: 4 };

enum BoardGameTurn {
    Move { squares: i32 },
    Pass,
}

let y: BoardGameTurn = BoardGameTurn::Move { squares: 1 };

Both variants are named Move, but since they’re scoped to the name of the enum, they can both be used without conflict.

A value of an enum type contains information about which variant it is, in addition to any data associated with that variant. This is sometimes referred to as a ‘tagged union’, since the data includes a ‘tag’ indicating what type it is. The compiler uses this information to enforce that you’re accessing the data in the enum safely. For instance, you can’t simply try to destructure a value as if it were one of the possible variants:

fn process_color_change(msg: Message) {
    let Message::ChangeColor(r, g, b) = msg; // compile-time error
}

Not supporting these operations may seem rather limiting, but it’s a limitation which we can overcome. There are two ways: by implementing equality ourselves, or by pattern matching variants with [match]match expressions, which you’ll learn in the next section. We don’t know enough about Rust to implement equality yet, but we’ll find out in the [traits]traits section.

Constructors as functions

An enum constructor can also be used like a function. For example:

# enum Message {
# Write(String),
# }
let m = Message::Write("Hello, world".to_string());

is the same as

# enum Message {
# Write(String),
# }
fn foo(x: String) -> Message {
    Message::Write(x)
}

let x = foo("Hello, world".to_string());

This is not immediately useful to us, but when we get to [closures]closures, we’ll talk about passing functions as arguments to other functions. For example, with [iterators]iterators, we can do this to convert a vector of Strings into a vector of Message::Writes:

# enum Message {
# Write(String),
# }

let v = vec!["Hello".to_string(), "World".to_string()];

let v1: Vec<Message> = v.into_iter().map(Message::Write).collect();

Crates and Modules

When a project starts getting large, it’s considered good software engineering practice to split it up into a bunch of smaller pieces, and then fit them together. It’s also important to have a well-defined interface, so that some of your functionality is private, and some is public. To facilitate these kinds of things, Rust has a module system.

Basic terminology: Crates and Modules

Rust has two distinct terms that relate to the module system: ‘crate’ and ‘module’. A crate is synonymous with a ‘library’ or ‘package’ in other languages. Hence “Cargo” as the name of Rust’s package management tool: you ship your crates to others with Cargo. Crates can produce an executable or a library, depending on the project.

Each crate has an implicit root module that contains the code for that crate. You can then define a tree of sub-modules under that root module. Modules allow you to partition your code within the crate itself.

As an example, let’s make a phrases crate, which will give us various phrases in different languages. To keep things simple, we’ll stick to ‘greetings’ and ‘farewells’ as two kinds of phrases, and use English and Japanese (日本語) as two languages for those phrases to be in. We’ll use this module layout:

                                    +-----------+
                                +---| greetings |
                                |   +-----------+
                  +---------+   |
              +---| english |---+
              |   +---------+   |   +-----------+
              |                 +---| farewells |
+---------+   |                     +-----------+
| phrases |---+
+---------+   |                     +-----------+
              |                 +---| greetings |
              |   +----------+  |   +-----------+
              +---| japanese |--+
                  +----------+  |
                                |   +-----------+
                                +---| farewells |
                                    +-----------+

In this example, phrases is the name of our crate. All of the rest are modules. You can see that they form a tree, branching out from the crate root, which is the root of the tree: phrases itself.

Now that we have a plan, let’s define these modules in code. To start, generate a new crate with Cargo:

$ cargo new phrases
$ cd phrases

If you remember, this generates a simple project for us:

$ tree .
.
├── Cargo.toml
└── src
    └── lib.rs

1 directory, 2 files

src/lib.rs is our crate root, corresponding to the phrases in our diagram above.

Defining Modules

To define each of our modules, we use the mod keyword. Let’s make our src/lib.rs look like this:

mod english {
    mod greetings {
    }

    mod farewells {
    }
}

mod japanese {
    mod greetings {
    }

    mod farewells {
    }
}

After the mod keyword, you give the name of the module. Module names follow the conventions for other Rust identifiers: lower_snake_case. The contents of each module are within curly braces ({}).

Within a given mod, you can declare sub-mods. We can refer to sub-modules with double-colon (::) notation: our four nested modules are english::greetings, english::farewells, japanese::greetings, and japanese::farewells. Because these sub-modules are namespaced under their parent module, the names don’t conflict: english::greetings and japanese::greetings are distinct, even though their names are both greetings.

Because this crate does not have a main() function, and is called lib.rs, Cargo will build this crate as a library:

$ cargo build
   Compiling phrases v0.0.1 (file:///home/you/projects/phrases)
$ ls target/debug
build  deps  examples  libphrases-a7448e02a0468eaa.rlib  native

libphrases-hash.rlib is the compiled crate. Before we see how to use this crate from another crate, let’s break it up into multiple files.

Multiple file crates

If each crate were just one file, these files would get very large. It’s often easier to split up crates into multiple files, and Rust supports this in two ways.

Instead of declaring a module like this:

mod english {
    // contents of our module go here
}

We can instead declare our module like this:

mod english;

If we do that, Rust will expect to find either a english.rs file, or a english/mod.rs file with the contents of our module.

Note that in these files, you don’t need to re-declare the module: that’s already been done with the initial mod declaration.

Using these two techniques, we can break up our crate into two directories and seven files:

$ tree .
.
├── Cargo.lock
├── Cargo.toml
├── src
│   ├── english
│   │   ├── farewells.rs
│   │   ├── greetings.rs
│   │   └── mod.rs
│   ├── japanese
│   │   ├── farewells.rs
│   │   ├── greetings.rs
│   │   └── mod.rs
│   └── lib.rs
└── target
    └── debug
        ├── build
        ├── deps
        ├── examples
        ├── libphrases-a7448e02a0468eaa.rlib
        └── native

src/lib.rs is our crate root, and looks like this:

mod english;
mod japanese;

These two declarations tell Rust to look for either src/english.rs and src/japanese.rs, or src/english/mod.rs and src/japanese/mod.rs, depending on our preference. In this case, because our modules have sub-modules, we’ve chosen the second. Both src/english/mod.rs and src/japanese/mod.rs look like this:

mod greetings;
mod farewells;

Again, these declarations tell Rust to look for either src/english/greetings.rs and src/japanese/greetings.rs or src/english/farewells/mod.rs and src/japanese/farewells/mod.rs. Because these sub-modules don’t have their own sub-modules, we’ve chosen to make them src/english/greetings.rs and src/japanese/farewells.rs. Whew!

The contents of src/english/greetings.rs and src/japanese/farewells.rs are both empty at the moment. Let’s add some functions.

Put this in src/english/greetings.rs:

fn hello() -> String {
    "Hello!".to_string()
}

Put this in src/english/farewells.rs:

fn goodbye() -> String {
    "Goodbye.".to_string()
}

Put this in src/japanese/greetings.rs:

fn hello() -> String {
    "こんにちは".to_string()
}

Of course, you can copy and paste this from this web page, or just type something else. It’s not important that you actually put ‘konnichiwa’ to learn about the module system.

Put this in src/japanese/farewells.rs:

fn goodbye() -> String {
    "さようなら".to_string()
}

(This is ‘Sayōnara’, if you’re curious.)

Now that we have some functionality in our crate, let’s try to use it from another crate.

Importing External Crates

We have a library crate. Let’s make an executable crate that imports and uses our library.

Make a src/main.rs and put this in it (it won’t quite compile yet):

extern crate phrases;

fn main() {
    println!("Hello in English: {}", phrases::english::greetings::hello());
    println!("Goodbye in English: {}", phrases::english::farewells::goodbye());

    println!("Hello in Japanese: {}", phrases::japanese::greetings::hello());
    println!("Goodbye in Japanese: {}", phrases::japanese::farewells::goodbye());
}

The extern crate declaration tells Rust that we need to compile and link to the phrases crate. We can then use phrases’ modules in this one. As we mentioned earlier, you can use double colons to refer to sub-modules and the functions inside of them.

(Note: when importing a crate that has dashes in its name "like-this", which is not a valid Rust identifier, it will be converted by changing the dashes to underscores, so you would write extern crate like_this;.)

Also, Cargo assumes that src/main.rs is the crate root of a binary crate, rather than a library crate. Our package now has two crates: src/lib.rs and src/main.rs. This pattern is quite common for executable crates: most functionality is in a library crate, and the executable crate uses that library. This way, other programs can also use the library crate, and it’s also a nice separation of concerns.

This doesn’t quite work yet, though. We get four errors that look similar to this:

$ cargo build
   Compiling phrases v0.0.1 (file:///home/you/projects/phrases)
src/main.rs:4:38: 4:72 error: function `hello` is private
src/main.rs:4     println!("Hello in English: {}", phrases::english::greetings::hello());
                                                   ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
note: in expansion of format_args!
<std macros>:2:25: 2:58 note: expansion site
<std macros>:1:1: 2:62 note: in expansion of print!
<std macros>:3:1: 3:54 note: expansion site
<std macros>:1:1: 3:58 note: in expansion of println!
phrases/src/main.rs:4:5: 4:76 note: expansion site

By default, everything is private in Rust. Let’s talk about this in some more depth.

Exporting a Public Interface

Rust allows you to precisely control which aspects of your interface are public, and so private is the default. To make things public, you use the pub keyword. Let’s focus on the english module first, so let’s reduce our src/main.rs to just this:

extern crate phrases;

fn main() {
    println!("Hello in English: {}", phrases::english::greetings::hello());
    println!("Goodbye in English: {}", phrases::english::farewells::goodbye());
}

In our src/lib.rs, let’s add pub to the english module declaration:

pub mod english;
mod japanese;

And in our src/english/mod.rs, let’s make both pub:

pub mod greetings;
pub mod farewells;

In our src/english/greetings.rs, let’s add pub to our fn declaration:

pub fn hello() -> String {
    "Hello!".to_string()
}

And also in src/english/farewells.rs:

pub fn goodbye() -> String {
    "Goodbye.".to_string()
}

Now, our crate compiles, albeit with warnings about not using the japanese functions:

$ cargo run
   Compiling phrases v0.0.1 (file:///home/you/projects/phrases)
src/japanese/greetings.rs:1:1: 3:2 warning: function is never used: `hello`, #[warn(dead_code)] on by default
src/japanese/greetings.rs:1 fn hello() -> String {
src/japanese/greetings.rs:2     "こんにちは".to_string()
src/japanese/greetings.rs:3 }
src/japanese/farewells.rs:1:1: 3:2 warning: function is never used: `goodbye`, #[warn(dead_code)] on by default
src/japanese/farewells.rs:1 fn goodbye() -> String {
src/japanese/farewells.rs:2     "さようなら".to_string()
src/japanese/farewells.rs:3 }
     Running `target/debug/phrases`
Hello in English: Hello!
Goodbye in English: Goodbye.

pub also applies to structs and their member fields. In keeping with Rust’s tendency toward safety, simply making a struct public won't automatically make its members public: you must mark the fields individually with pub.

Now that our functions are public, we can use them. Great! However, typing out phrases::english::greetings::hello() is very long and repetitive. Rust has another keyword for importing names into the current scope, so that you can refer to them with shorter names. Let’s talk about use.

Importing Modules with use

Rust has a use keyword, which allows us to import names into our local scope. Let’s change our src/main.rs to look like this:

extern crate phrases;

use phrases::english::greetings;
use phrases::english::farewells;

fn main() {
    println!("Hello in English: {}", greetings::hello());
    println!("Goodbye in English: {}", farewells::goodbye());
}

The two use lines import each module into the local scope, so we can refer to the functions by a much shorter name. By convention, when importing functions, it’s considered best practice to import the module, rather than the function directly. In other words, you can do this:

extern crate phrases;

use phrases::english::greetings::hello;
use phrases::english::farewells::goodbye;

fn main() {
    println!("Hello in English: {}", hello());
    println!("Goodbye in English: {}", goodbye());
}

But it is not idiomatic. This is significantly more likely to introduce a naming conflict. In our short program, it’s not a big deal, but as it grows, it becomes a problem. If we have conflicting names, Rust will give a compilation error. For example, if we made the japanese functions public, and tried to do this:

extern crate phrases;

use phrases::english::greetings::hello;
use phrases::japanese::greetings::hello;

fn main() {
    println!("Hello in English: {}", hello());
    println!("Hello in Japanese: {}", hello());
}

Rust will give us a compile-time error:

   Compiling phrases v0.0.1 (file:///home/you/projects/phrases)
src/main.rs:4:5: 4:40 error: a value named `hello` has already been imported in this module [E0252]
src/main.rs:4 use phrases::japanese::greetings::hello;
                  ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
error: aborting due to previous error
Could not compile `phrases`.

If we’re importing multiple names from the same module, we don’t have to type it out twice. Instead of this:

use phrases::english::greetings;
use phrases::english::farewells;

We can use this shortcut:

use phrases::english::{greetings, farewells};

Re-exporting with pub use

You don’t just use use to shorten identifiers. You can also use it inside of your crate to re-export a function inside another module. This allows you to present an external interface that may not directly map to your internal code organization.

Let’s look at an example. Modify your src/main.rs to read like this:

extern crate phrases;

use phrases::english::{greetings,farewells};
use phrases::japanese;

fn main() {
    println!("Hello in English: {}", greetings::hello());
    println!("Goodbye in English: {}", farewells::goodbye());

    println!("Hello in Japanese: {}", japanese::hello());
    println!("Goodbye in Japanese: {}", japanese::goodbye());
}

Then, modify your src/lib.rs to make the japanese mod public:

pub mod english;
pub mod japanese;

Next, make the two functions public, first in src/japanese/greetings.rs:

pub fn hello() -> String {
    "こんにちは".to_string()
}

And then in src/japanese/farewells.rs:

pub fn goodbye() -> String {
    "さようなら".to_string()
}

Finally, modify your src/japanese/mod.rs to read like this:

pub use self::greetings::hello;
pub use self::farewells::goodbye;

mod greetings;
mod farewells;

The pub use declaration brings the function into scope at this part of our module hierarchy. Because we’ve pub used this inside of our japanese module, we now have a phrases::japanese::hello() function and a phrases::japanese::goodbye() function, even though the code for them lives in phrases::japanese::greetings::hello() and phrases::japanese::farewells::goodbye(). Our internal organization doesn’t define our external interface.

Here we have a pub use for each function we want to bring into the japanese scope. We could alternatively use the wildcard syntax to include everything from greetings into the current scope: pub use self::greetings::*.

What about the self? Well, by default, use declarations are absolute paths, starting from your crate root. self makes that path relative to your current place in the hierarchy instead. There’s one more special form of use: you can use super:: to reach one level up the tree from your current location. Some people like to think of self as . and super as .., from many shells’ display for the current directory and the parent directory.

Outside of use, paths are relative: foo::bar() refers to a function inside of foo relative to where we are. If that’s prefixed with ::, as in ::foo::bar(), it refers to a different foo, an absolute path from your crate root.

This will build and run:

$ cargo run
   Compiling phrases v0.0.1 (file:///home/you/projects/phrases)
     Running `target/debug/phrases`
Hello in English: Hello!
Goodbye in English: Goodbye.
Hello in Japanese: こんにちは
Goodbye in Japanese: さようなら

Complex imports

Rust offers several advanced options that can add compactness and convenience to your extern crate and use statements. Here is an example:

extern crate phrases as sayings;

use sayings::japanese::greetings as ja_greetings;
use sayings::japanese::farewells::*;
use sayings::english::{self, greetings as en_greetings, farewells as en_farewells};

fn main() {
    println!("Hello in English; {}", en_greetings::hello());
    println!("And in Japanese: {}", ja_greetings::hello());
    println!("Goodbye in English: {}", english::farewells::goodbye());
    println!("Again: {}", en_farewells::goodbye());
    println!("And in Japanese: {}", goodbye());
}

What's going on here?

First, both extern crate and use allow renaming the thing that is being imported. So the crate is still called "phrases", but here we will refer to it as "sayings". Similarly, the first use statement pulls in the japanese::greetings module from the crate, but makes it available as ja_greetings as opposed to simply greetings. This can help to avoid ambiguity when importing similarly-named items from different places.

The second use statement uses a star glob to bring in all symbols from the sayings::japanese::farewells module. As you can see we can later refer to the Japanese goodbye function with no module qualifiers. This kind of glob should be used sparingly.

The third use statement bears more explanation. It's using "brace expansion" globbing to compress three use statements into one (this sort of syntax may be familiar if you've written Linux shell scripts before). The uncompressed form of this statement would be:

use sayings::english;
use sayings::english::greetings as en_greetings;
use sayings::english::farewells as en_farewells;

As you can see, the curly brackets compress use statements for several items under the same path, and in this context self just refers back to that path. Note: The curly brackets cannot be nested or mixed with star globbing.

Error Handling

Basic Collections

Vectors

A ‘vector’ is a dynamic or ‘growable’ array, implemented as the standard library type [Vec<T>]vec. The T means that we can have vectors of any type (see the chapter on generics for more). Vectors always allocate their data on the heap. You can create them with the vec! macro:

let v = vec![1, 2, 3, 4, 5]; // v: Vec<i32>

(Notice that unlike the println! macro we’ve used in the past, we use square brackets [] with vec! macro. Rust allows you to use either in either situation, this is just convention.)

There’s an alternate form of vec! for repeating an initial value:

let v = vec![0; 10]; // ten zeroes

Accessing elements

To get the value at a particular index in the vector, we use []s:

let v = vec![1, 2, 3, 4, 5];

println!("The third element of v is {}", v[2]);

The indices count from 0, so the third element is v[2].

It’s also important to note that you must index with the usize type:

let v = vec![1, 2, 3, 4, 5];

let i: usize = 0;
let j: i32 = 0;

// works
v[i];

// doesn’t
v[j];

Indexing with a non-usize type gives an error that looks like this:

error: the trait `core::ops::Index<i32>` is not implemented for the type
`collections::vec::Vec<_>` [E0277]
v[j];
^~~~
note: the type `collections::vec::Vec<_>` cannot be indexed by `i32`
error: aborting due to previous error

There’s a lot of punctuation in that message, but the core of it makes sense: you cannot index with an i32.

Iterating

Once you have a vector, you can iterate through its elements with for. There are three versions:

let mut v = vec![1, 2, 3, 4, 5];

for i in &v {
    println!("A reference to {}", i);
}

for i in &mut v {
    println!("A mutable reference to {}", i);
}

for i in v {
    println!("Take ownership of the vector and its element {}", i);
}

Vectors have many more useful methods, which you can read about in their API documentation.

Strings

HashMap<K, V>

Traits

A trait is a language feature that tells the Rust compiler about functionality a type must provide.

Recall the impl keyword, used to call a function with method syntax:

struct Circle {
    x: f64,
    y: f64,
    radius: f64,
}

impl Circle {
    fn area(&self) -> f64 {
        std::f64::consts::PI * (self.radius * self.radius)
    }
}

Traits are similar, except that we first define a trait with a method signature, then implement the trait for a type. In this example, we implement the trait HasArea for Circle:

struct Circle {
    x: f64,
    y: f64,
    radius: f64,
}

trait HasArea {
    fn area(&self) -> f64;
}

impl HasArea for Circle {
    fn area(&self) -> f64 {
        std::f64::consts::PI * (self.radius * self.radius)
    }
}

As you can see, the trait block looks very similar to the impl block, but we don’t define a body, just a type signature. When we impl a trait, we use impl Trait for Item, rather than just impl Item.

Trait bounds on generic functions

Traits are useful because they allow a type to make certain promises about its behavior. Generic functions can exploit this to constrain, or bound, the types they accept. Consider this function, which does not compile:

fn print_area<T>(shape: T) {
    println!("This shape has an area of {}", shape.area());
}

Rust complains:

error: no method named `area` found for type `T` in the current scope

Because T can be any type, we can’t be sure that it implements the area method. But we can add a trait bound to our generic T, ensuring that it does:

# trait HasArea {
#     fn area(&self) -> f64;
# }
fn print_area<T: HasArea>(shape: T) {
    println!("This shape has an area of {}", shape.area());
}

The syntax <T: HasArea> means “any type that implements the HasArea trait.” Because traits define function type signatures, we can be sure that any type which implements HasArea will have an .area() method.

Here’s an extended example of how this works:

trait HasArea {
    fn area(&self) -> f64;
}

struct Circle {
    x: f64,
    y: f64,
    radius: f64,
}

impl HasArea for Circle {
    fn area(&self) -> f64 {
        std::f64::consts::PI * (self.radius * self.radius)
    }
}

struct Square {
    x: f64,
    y: f64,
    side: f64,
}

impl HasArea for Square {
    fn area(&self) -> f64 {
        self.side * self.side
    }
}

fn print_area<T: HasArea>(shape: T) {
    println!("This shape has an area of {}", shape.area());
}

fn main() {
    let c = Circle {
        x: 0.0f64,
        y: 0.0f64,
        radius: 1.0f64,
    };

    let s = Square {
        x: 0.0f64,
        y: 0.0f64,
        side: 1.0f64,
    };

    print_area(c);
    print_area(s);
}

This program outputs:

This shape has an area of 3.141593
This shape has an area of 1

As you can see, print_area is now generic, but also ensures that we have passed in the correct types. If we pass in an incorrect type:

print_area(5);

We get a compile-time error:

error: the trait `HasArea` is not implemented for the type `_` [E0277]

Trait bounds on generic structs

Your generic structs can also benefit from trait bounds. All you need to do is append the bound when you declare type parameters. Here is a new type Rectangle<T> and its operation is_square():

struct Rectangle<T> {
    x: T,
    y: T,
    width: T,
    height: T,
}

impl<T: PartialEq> Rectangle<T> {
    fn is_square(&self) -> bool {
        self.width == self.height
    }
}

fn main() {
    let mut r = Rectangle {
        x: 0,
        y: 0,
        width: 47,
        height: 47,
    };

    assert!(r.is_square());

    r.height = 42;
    assert!(!r.is_square());
}

is_square() needs to check that the sides are equal, so the sides must be of a type that implements the [core::cmp::PartialEq]PartialEq trait:

impl<T: PartialEq> Rectangle<T> { ... }

Now, a rectangle can be defined in terms of any type that can be compared for equality.

Here we defined a new struct Rectangle that accepts numbers of any precision—really, objects of pretty much any type—as long as they can be compared for equality. Could we do the same for our HasArea structs, Square and Circle? Yes, but they need multiplication, and to work with that we need to know more about operator traits.

Rules for implementing traits

So far, we’ve only added trait implementations to structs, but you can implement a trait for any type. So technically, we could implement HasArea for i32:

trait HasArea {
    fn area(&self) -> f64;
}

impl HasArea for i32 {
    fn area(&self) -> f64 {
        println!("this is silly");

        *self as f64
    }
}

5.area();

It is considered poor style to implement methods on such primitive types, even though it is possible.

This may seem like the Wild West, but there are two restrictions around implementing traits that prevent this from getting out of hand. The first is that if the trait isn’t defined in your scope, it doesn’t apply. Here’s an example: the standard library provides a [Write]write trait which adds extra functionality to Files, for doing file I/O. By default, a File won’t have its methods:

let mut f = std::fs::File::open("foo.txt").expect("Couldn’t open foo.txt");
let buf = b"whatever"; // byte string literal. buf: &[u8; 8]
let result = f.write(buf);
# result.unwrap(); // ignore the error

Here’s the error:

error: type `std::fs::File` does not implement any method in scope named `write`
let result = f.write(buf);
               ^~~~~~~~~~

We need to use the Write trait first:

use std::io::Write;

let mut f = std::fs::File::open("foo.txt").expect("Couldn’t open foo.txt");
let buf = b"whatever";
let result = f.write(buf);
# result.unwrap(); // ignore the error

This will compile without error.

This means that even if someone does something bad like add methods to i32, it won’t affect you, unless you use that trait.

There’s one more restriction on implementing traits: either the trait, or the type you’re writing the impl for, must be defined by you. So, we could implement the HasArea type for i32, because HasArea is in our code. But if we tried to implement ToString, a trait provided by Rust, for i32, we could not, because neither the trait nor the type are in our code.

One last thing about traits: generic functions with a trait bound use ‘monomorphization’ (mono: one, morph: form), so they are statically dispatched. What’s that mean? Check out the chapter on trait objects for more details.

Multiple trait bounds

You’ve seen that you can bound a generic type parameter with a trait:

fn foo<T: Clone>(x: T) {
    x.clone();
}

If you need more than one bound, you can use +:

use std::fmt::Debug;

fn foo<T: Clone + Debug>(x: T) {
    x.clone();
    println!("{:?}", x);
}

T now needs to be both Clone as well as Debug.

Where clause

Writing functions with only a few generic types and a small number of trait bounds isn’t too bad, but as the number increases, the syntax gets increasingly awkward:

use std::fmt::Debug;

fn foo<T: Clone, K: Clone + Debug>(x: T, y: K) {
    x.clone();
    y.clone();
    println!("{:?}", y);
}

The name of the function is on the far left, and the parameter list is on the far right. The bounds are getting in the way.

Rust has a solution, and it’s called a ‘where clause’:

use std::fmt::Debug;

fn foo<T: Clone, K: Clone + Debug>(x: T, y: K) {
    x.clone();
    y.clone();
    println!("{:?}", y);
}

fn bar<T, K>(x: T, y: K) where T: Clone, K: Clone + Debug {
    x.clone();
    y.clone();
    println!("{:?}", y);
}

fn main() {
    foo("Hello", "world");
    bar("Hello", "world");
}

foo() uses the syntax we showed earlier, and bar() uses a where clause. All you need to do is leave off the bounds when defining your type parameters, and then add where after the parameter list. For longer lists, whitespace can be added:

use std::fmt::Debug;

fn bar<T, K>(x: T, y: K)
    where T: Clone,
          K: Clone + Debug {

    x.clone();
    y.clone();
    println!("{:?}", y);
}

This flexibility can add clarity in complex situations.

where is also more powerful than the simpler syntax. For example:

trait ConvertTo<Output> {
    fn convert(&self) -> Output;
}

impl ConvertTo<i64> for i32 {
    fn convert(&self) -> i64 { *self as i64 }
}

// can be called with T == i32
fn normal<T: ConvertTo<i64>>(x: &T) -> i64 {
    x.convert()
}

// can be called with T == i64
fn inverse<T>() -> T
        // this is using ConvertTo as if it were "ConvertTo<i64>"
        where i32: ConvertTo<T> {
    42.convert()
}

This shows off the additional feature of where clauses: they allow bounds on the left-hand side not only of type parameters T, but also of types (i32 in this case). In this example, i32 must implement ConvertTo<T>. Rather than defining what i32 is (since that's obvious), the where clause here constrains T.

Default methods

A default method can be added to a trait definition if it is already known how a typical implementor will define a method. For example, is_invalid() is defined as the opposite of is_valid():

trait Foo {
    fn is_valid(&self) -> bool;

    fn is_invalid(&self) -> bool { !self.is_valid() }
}

Implementors of the Foo trait need to implement is_valid() but not is_invalid() due to the added default behavior. This default behavior can still be overridden as in:

# trait Foo {
#     fn is_valid(&self) -> bool;
#
#     fn is_invalid(&self) -> bool { !self.is_valid() }
# }
struct UseDefault;

impl Foo for UseDefault {
    fn is_valid(&self) -> bool {
        println!("Called UseDefault.is_valid.");
        true
    }
}

struct OverrideDefault;

impl Foo for OverrideDefault {
    fn is_valid(&self) -> bool {
        println!("Called OverrideDefault.is_valid.");
        true
    }

    fn is_invalid(&self) -> bool {
        println!("Called OverrideDefault.is_invalid!");
        true // overrides the expected value of is_invalid()
    }
}

let default = UseDefault;
assert!(!default.is_invalid()); // prints "Called UseDefault.is_valid."

let over = OverrideDefault;
assert!(over.is_invalid()); // prints "Called OverrideDefault.is_invalid!"

Inheritance

Sometimes, implementing a trait requires implementing another trait:

trait Foo {
    fn foo(&self);
}

trait FooBar : Foo {
    fn foobar(&self);
}

Implementors of FooBar must also implement Foo, like this:

# trait Foo {
#     fn foo(&self);
# }
# trait FooBar : Foo {
#     fn foobar(&self);
# }
struct Baz;

impl Foo for Baz {
    fn foo(&self) { println!("foo"); }
}

impl FooBar for Baz {
    fn foobar(&self) { println!("foobar"); }
}

If we forget to implement Foo, Rust will tell us:

error: the trait `main::Foo` is not implemented for the type `main::Baz` [E0277]

Deriving

Implementing traits like Debug and Default repeatedly can become quite tedious. For that reason, Rust provides an attribute that allows you to let Rust automatically implement traits for you:

#[derive(Debug)]
struct Foo;

fn main() {
    println!("{:?}", Foo);
}

However, deriving is limited to a certain set of traits:

  • [Clone](../core/clone/trait.Clone.html)
  • [Copy](../core/marker/trait.Copy.html)
  • [Debug](../core/fmt/trait.Debug.html)
  • [Default](../core/default/trait.Default.html)
  • [Eq](../core/cmp/trait.Eq.html)
  • [Hash](../core/hash/trait.Hash.html)
  • [Ord](../core/cmp/trait.Ord.html)
  • [PartialEq](../core/cmp/trait.PartialEq.html)
  • [PartialOrd](../core/cmp/trait.PartialOrd.html)

Closures

Sometimes it is useful to wrap up a function and free variables for better clarity and reuse. The free variables that can be used come from the enclosing scope and are ‘closed over’ when used in the function. From this, we get the name ‘closures’ and Rust provides a really great implementation of them, as we’ll see.

Syntax

Closures look like this:

let plus_one = |x: i32| x + 1;

assert_eq!(2, plus_one(1));

We create a binding, plus_one, and assign it to a closure. The closure’s arguments go between the pipes (|), and the body is an expression, in this case, x + 1. Remember that { } is an expression, so we can have multi-line closures too:

let plus_two = |x| {
    let mut result: i32 = x;

    result += 1;
    result += 1;

    result
};

assert_eq!(4, plus_two(2));

You’ll notice a few things about closures that are a bit different from regular named functions defined with fn. The first is that we did not need to annotate the types of arguments the closure takes or the values it returns. We can:

let plus_one = |x: i32| -> i32 { x + 1 };

assert_eq!(2, plus_one(1));

But we don’t have to. Why is this? Basically, it was chosen for ergonomic reasons. While specifying the full type for named functions is helpful with things like documentation and type inference, the full type signatures of closures are rarely documented since they’re anonymous, and they don’t cause the kinds of error-at-a-distance problems that inferring named function types can.

The second is that the syntax is similar, but a bit different. I’ve added spaces here for easier comparison:

fn  plus_one_v1   (x: i32) -> i32 { x + 1 }
let plus_one_v2 = |x: i32| -> i32 { x + 1 };
let plus_one_v3 = |x: i32|          x + 1  ;

Small differences, but they’re similar.

Closures and their environment

The environment for a closure can include bindings from its enclosing scope in addition to parameters and local bindings. It looks like this:

let num = 5;
let plus_num = |x: i32| x + num;

assert_eq!(10, plus_num(5));

This closure, plus_num, refers to a let binding in its scope: num. More specifically, it borrows the binding. If we do something that would conflict with that binding, we get an error. Like this one:

let mut num = 5;
let plus_num = |x: i32| x + num;

let y = &mut num;

Which errors with:

error: cannot borrow `num` as mutable because it is also borrowed as immutable
    let y = &mut num;
                 ^~~
note: previous borrow of `num` occurs here due to use in closure; the immutable
  borrow prevents subsequent moves or mutable borrows of `num` until the borrow
  ends
    let plus_num = |x| x + num;
                   ^~~~~~~~~~~
note: previous borrow ends here
fn main() {
    let mut num = 5;
    let plus_num = |x| x + num;

    let y = &mut num;
}
^

A verbose yet helpful error message! As it says, we can’t take a mutable borrow on num because the closure is already borrowing it. If we let the closure go out of scope, we can:

let mut num = 5;
{
    let plus_num = |x: i32| x + num;

} // plus_num goes out of scope, borrow of num ends

let y = &mut num;

If your closure requires it, however, Rust will take ownership and move the environment instead. This doesn’t work:

let nums = vec![1, 2, 3];

let takes_nums = || nums;

println!("{:?}", nums);

We get this error:

note: `nums` moved into closure environment here because it has type
  `[closure(()) -> collections::vec::Vec<i32>]`, which is non-copyable
let takes_nums = || nums;
                 ^~~~~~~

Vec<T> has ownership over its contents, and therefore, when we refer to it in our closure, we have to take ownership of nums. It’s the same as if we’d passed nums to a function that took ownership of it.

move closures

We can force our closure to take ownership of its environment with the move keyword:

let num = 5;

let owns_num = move |x: i32| x + num;

Now, even though the keyword is move, the variables follow normal move semantics. In this case, 5 implements Copy, and so owns_num takes ownership of a copy of num. So what’s the difference?

let mut num = 5;

{
    let mut add_num = |x: i32| num += x;

    add_num(5);
}

assert_eq!(10, num);

So in this case, our closure took a mutable reference to num, and then when we called add_num, it mutated the underlying value, as we’d expect. We also needed to declare add_num as mut too, because we’re mutating its environment.

If we change to a move closure, it’s different:

let mut num = 5;

{
    let mut add_num = move |x: i32| num += x;

    add_num(5);
}

assert_eq!(5, num);

We only get 5. Rather than taking a mutable borrow out on our num, we took ownership of a copy.

Another way to think about move closures: they give a closure its own stack frame. Without move, a closure may be tied to the stack frame that created it, while a move closure is self-contained. This means that you cannot generally return a non-move closure from a function, for example.

But before we talk about taking and returning closures, we should talk some more about the way that closures are implemented. As a systems language, Rust gives you tons of control over what your code does, and closures are no different.

Closure implementation

Rust’s implementation of closures is a bit different than other languages. They are effectively syntax sugar for traits. You’ll want to make sure to have read the traits chapter before this one, as well as the chapter on trait objects.

Got all that? Good.

The key to understanding how closures work under the hood is something a bit strange: Using () to call a function, like foo(), is an overloadable operator. From this, everything else clicks into place. In Rust, we use the trait system to overload operators. Calling functions is no different. We have three separate traits to overload with:

# mod foo {
pub trait Fn<Args> : FnMut<Args> {
    extern "rust-call" fn call(&self, args: Args) -> Self::Output;
}

pub trait FnMut<Args> : FnOnce<Args> {
    extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output;
}

pub trait FnOnce<Args> {
    type Output;

    extern "rust-call" fn call_once(self, args: Args) -> Self::Output;
}
# }

You’ll notice a few differences between these traits, but a big one is self: Fn takes &self, FnMut takes &mut self, and FnOnce takes self. This covers all three kinds of self via the usual method call syntax. But we’ve split them up into three traits, rather than having a single one. This gives us a large amount of control over what kind of closures we can take.

The || {} syntax for closures is sugar for these three traits. Rust will generate a struct for the environment, impl the appropriate trait, and then use it.

Taking closures as arguments

Now that we know that closures are traits, we already know how to accept and return closures: just like any other trait!

This also means that we can choose static vs dynamic dispatch as well. First, let’s write a function which takes something callable, calls it, and returns the result:

fn call_with_one<F>(some_closure: F) -> i32
    where F : Fn(i32) -> i32 {

    some_closure(1)
}

let answer = call_with_one(|x| x + 2);

assert_eq!(3, answer);

We pass our closure, |x| x + 2, to call_with_one. It just does what it suggests: it calls the closure, giving it 1 as an argument.

Let’s examine the signature of call_with_one in more depth:

fn call_with_one<F>(some_closure: F) -> i32
#    where F : Fn(i32) -> i32 {
#    some_closure(1) }

We take one parameter, and it has the type F. We also return a i32. This part isn’t interesting. The next part is:

# fn call_with_one<F>(some_closure: F) -> i32
    where F : Fn(i32) -> i32 {
#   some_closure(1) }

Because Fn is a trait, we can bound our generic with it. In this case, our closure takes a i32 as an argument and returns an i32, and so the generic bound we use is Fn(i32) -> i32.

There’s one other key point here: because we’re bounding a generic with a trait, this will get monomorphized, and therefore, we’ll be doing static dispatch into the closure. That’s pretty neat. In many languages, closures are inherently heap allocated, and will always involve dynamic dispatch. In Rust, we can stack allocate our closure environment, and statically dispatch the call. This happens quite often with iterators and their adapters, which often take closures as arguments.

Of course, if we want dynamic dispatch, we can get that too. A trait object handles this case, as usual:

fn call_with_one(some_closure: &Fn(i32) -> i32) -> i32 {
    some_closure(1)
}

let answer = call_with_one(&|x| x + 2);

assert_eq!(3, answer);

Now we take a trait object, a &Fn. And we have to make a reference to our closure when we pass it to call_with_one, so we use &||.

Function pointers and closures

A function pointer is kind of like a closure that has no environment. As such, you can pass a function pointer to any function expecting a closure argument, and it will work:

fn call_with_one(some_closure: &Fn(i32) -> i32) -> i32 {
    some_closure(1)
}

fn add_one(i: i32) -> i32 {
    i + 1
}

let f = add_one;

let answer = call_with_one(&f);

assert_eq!(2, answer);

In this example, we don’t strictly need the intermediate variable f, the name of the function works just fine too:

let answer = call_with_one(&add_one);

Returning closures

It’s very common for functional-style code to return closures in various situations. If you try to return a closure, you may run into an error. At first, it may seem strange, but we’ll figure it out. Here’s how you’d probably try to return a closure from a function:

fn factory() -> (Fn(i32) -> i32) {
    let num = 5;

    |x| x + num
}

let f = factory();

let answer = f(1);
assert_eq!(6, answer);

This gives us these long, related errors:

error: the trait `core::marker::Sized` is not implemented for the type
`core::ops::Fn(i32) -> i32` [E0277]
fn factory() -> (Fn(i32) -> i32) {
                ^~~~~~~~~~~~~~~~
note: `core::ops::Fn(i32) -> i32` does not have a constant size known at compile-time
fn factory() -> (Fn(i32) -> i32) {
                ^~~~~~~~~~~~~~~~
error: the trait `core::marker::Sized` is not implemented for the type `core::ops::Fn(i32) -> i32` [E0277]
let f = factory();
    ^
note: `core::ops::Fn(i32) -> i32` does not have a constant size known at compile-time
let f = factory();
    ^

In order to return something from a function, Rust needs to know what size the return type is. But since Fn is a trait, it could be various things of various sizes: many different types can implement Fn. An easy way to give something a size is to take a reference to it, as references have a known size. So we’d write this:

fn factory() -> &(Fn(i32) -> i32) {
    let num = 5;

    |x| x + num
}

let f = factory();

let answer = f(1);
assert_eq!(6, answer);

But we get another error:

error: missing lifetime specifier [E0106]
fn factory() -> &(Fn(i32) -> i32) {
                ^~~~~~~~~~~~~~~~~

Right. Because we have a reference, we need to give it a lifetime. But our factory() function takes no arguments, so elision doesn’t kick in here. Then what choices do we have? Try 'static:

fn factory() -> &'static (Fn(i32) -> i32) {
    let num = 5;

    |x| x + num
}

let f = factory();

let answer = f(1);
assert_eq!(6, answer);

But we get another error:

error: mismatched types:
 expected `&'static core::ops::Fn(i32) -> i32`,
    found `[closure@<anon>:7:9: 7:20]`
(expected &-ptr,
    found closure) [E0308]
         |x| x + num
         ^~~~~~~~~~~

This error is letting us know that we don’t have a &'static Fn(i32) -> i32, we have a [closure@<anon>:7:9: 7:20]. Wait, what?

Because each closure generates its own environment struct and implementation of Fn and friends, these types are anonymous. They exist just solely for this closure. So Rust shows them as closure@<anon>, rather than some autogenerated name.

The error also points out that the return type is expected to be a reference, but what we are trying to return is not. Further, we cannot directly assign a 'static lifetime to an object. So we'll take a different approach and return a ‘trait object’ by Boxing up the Fn. This almost works:

fn factory() -> Box<Fn(i32) -> i32> {
    let num = 5;

    Box::new(|x| x + num)
}
# fn main() {
let f = factory();

let answer = f(1);
assert_eq!(6, answer);
# }

There’s just one last problem:

error: closure may outlive the current function, but it borrows `num`,
which is owned by the current function [E0373]
Box::new(|x| x + num)
         ^~~~~~~~~~~

Well, as we discussed before, closures borrow their environment. And in this case, our environment is based on a stack-allocated 5, the num variable binding. So the borrow has a lifetime of the stack frame. So if we returned this closure, the function call would be over, the stack frame would go away, and our closure is capturing an environment of garbage memory! With one last fix, we can make this work:

fn factory() -> Box<Fn(i32) -> i32> {
    let num = 5;

    Box::new(move |x| x + num)
}
# fn main() {
let f = factory();

let answer = f(1);
assert_eq!(6, answer);
# }

By making the inner closure a move Fn, we create a new stack frame for our closure. By Boxing it up, we’ve given it a known size, and allowing it to escape our stack frame.

Iterators

Let's talk about loops.

Remember Rust's for loop? Here's an example:

for x in 0..10 {
    println!("{}", x);
}

Now that you know more Rust, we can talk in detail about how this works. Ranges (the 0..10) are 'iterators'. An iterator is something that we can call the .next() method on repeatedly, and it gives us a sequence of things.

Like this:

let mut range = 0..10;

loop {
    match range.next() {
        Some(x) => {
            println!("{}", x);
        },
        None => { break }
    }
}

We make a mutable binding to the range, which is our iterator. We then loop, with an inner match. This match is used on the result of range.next(), which gives us a reference to the next value of the iterator. next returns an Option<i32>, in this case, which will be Some(i32) when we have a value and None once we run out. If we get Some(i32), we print it out, and if we get None, we break out of the loop.

This code sample is basically the same as our for loop version. The for loop is just a handy way to write this loop/match/break construct.

for loops aren't the only thing that uses iterators, however. Writing your own iterator involves implementing the Iterator trait. While doing that is outside of the scope of this guide, Rust provides a number of useful iterators to accomplish various tasks. But first, a few notes about limitations of ranges.

Ranges are very primitive, and we often can use better alternatives. Consider the following Rust anti-pattern: using ranges to emulate a C-style for loop. Let’s suppose you needed to iterate over the contents of a vector. You may be tempted to write this:

let nums = vec![1, 2, 3];

for i in 0..nums.len() {
    println!("{}", nums[i]);
}

This is strictly worse than using an actual iterator. You can iterate over vectors directly, so write this:

let nums = vec![1, 2, 3];

for num in &nums {
    println!("{}", num);
}

There are two reasons for this. First, this more directly expresses what we mean. We iterate through the entire vector, rather than iterating through indexes, and then indexing the vector. Second, this version is more efficient: the first version will have extra bounds checking because it used indexing, nums[i]. But since we yield a reference to each element of the vector in turn with the iterator, there's no bounds checking in the second example. This is very common with iterators: we can ignore unnecessary bounds checks, but still know that we're safe.

There's another detail here that's not 100% clear because of how println! works. num is actually of type &i32. That is, it's a reference to an i32, not an i32 itself. println! handles the dereferencing for us, so we don't see it. This code works fine too:

let nums = vec![1, 2, 3];

for num in &nums {
    println!("{}", *num);
}

Now we're explicitly dereferencing num. Why does &nums give us references? Firstly, because we explicitly asked it to with &. Secondly, if it gave us the data itself, we would have to be its owner, which would involve making a copy of the data and giving us the copy. With references, we're just borrowing a reference to the data, and so it's just passing a reference, without needing to do the move.

So, now that we've established that ranges are often not what you want, let's talk about what you do want instead.

There are three broad classes of things that are relevant here: iterators, iterator adaptors, and consumers. Here's some definitions:

  • iterators give you a sequence of values.
  • iterator adaptors operate on an iterator, producing a new iterator with a different output sequence.
  • consumers operate on an iterator, producing some final set of values.

Let's talk about consumers first, since you've already seen an iterator, ranges.

Consumers

A consumer operates on an iterator, returning some kind of value or values. The most common consumer is collect(). This code doesn't quite compile, but it shows the intention:

let one_to_one_hundred = (1..101).collect();

As you can see, we call collect() on our iterator. collect() takes as many values as the iterator will give it, and returns a collection of the results. So why won't this compile? Rust can't determine what type of things you want to collect, and so you need to let it know. Here's the version that does compile:

let one_to_one_hundred = (1..101).collect::<Vec<i32>>();

If you remember, the ::<> syntax allows us to give a type hint, and so we tell it that we want a vector of integers. You don't always need to use the whole type, though. Using a _ will let you provide a partial hint:

let one_to_one_hundred = (1..101).collect::<Vec<_>>();

This says "Collect into a Vec<T>, please, but infer what the T is for me." _ is sometimes called a "type placeholder" for this reason.

collect() is the most common consumer, but there are others too. find() is one:

let greater_than_forty_two = (0..100)
                             .find(|x| *x > 42);

match greater_than_forty_two {
    Some(_) => println!("Found a match!"),
    None => println!("No match found :("),
}

find takes a closure, and works on a reference to each element of an iterator. This closure returns true if the element is the element we're looking for, and false otherwise. find returns the first element satisfying the specified predicate. Because we might not find a matching element, find returns an Option rather than the element itself.

Another important consumer is fold. Here's what it looks like:

let sum = (1..4).fold(0, |sum, x| sum + x);

fold() is a consumer that looks like this: fold(base, |accumulator, element| ...). It takes two arguments: the first is an element called the base. The second is a closure that itself takes two arguments: the first is called the accumulator, and the second is an element. Upon each iteration, the closure is called, and the result is the value of the accumulator on the next iteration. On the first iteration, the base is the value of the accumulator.

Okay, that's a bit confusing. Let's examine the values of all of these things in this iterator:

| base | accumulator | element | closure result | |------|-------------|---------|----------------| | 0 | 0 | 1 | 1 | | 0 | 1 | 2 | 3 | | 0 | 3 | 3 | 6 |

We called fold() with these arguments:

# (1..4)
.fold(0, |sum, x| sum + x);

So, 0 is our base, sum is our accumulator, and x is our element. On the first iteration, we set sum to 0, and x is the first element of nums, 1. We then add sum and x, which gives us 0 + 1 = 1. On the second iteration, that value becomes our accumulator, sum, and the element is the second element of the array, 2. 1 + 2 = 3, and so that becomes the value of the accumulator for the last iteration. On that iteration, x is the last element, 3, and 3 + 3 = 6, which is our final result for our sum. 1 + 2 + 3 = 6, and that's the result we got.

Whew. fold can be a bit strange the first few times you see it, but once it clicks, you can use it all over the place. Any time you have a list of things, and you want a single result, fold is appropriate.

Consumers are important due to one additional property of iterators we haven't talked about yet: laziness. Let's talk some more about iterators, and you'll see why consumers matter.

Iterators

As we've said before, an iterator is something that we can call the .next() method on repeatedly, and it gives us a sequence of things. Because you need to call the method, this means that iterators can be lazy and not generate all of the values upfront. This code, for example, does not actually generate the numbers 1-99, instead creating a value that merely represents the sequence:

let nums = 1..100;

Since we didn't do anything with the range, it didn't generate the sequence. Let's add the consumer:

let nums = (1..100).collect::<Vec<i32>>();

Now, collect() will require that the range gives it some numbers, and so it will do the work of generating the sequence.

Ranges are one of two basic iterators that you'll see. The other is iter(). iter() can turn a vector into a simple iterator that gives you each element in turn:

let nums = vec![1, 2, 3];

for num in nums.iter() {
   println!("{}", num);
}

These two basic iterators should serve you well. There are some more advanced iterators, including ones that are infinite.

That's enough about iterators. Iterator adaptors are the last concept we need to talk about with regards to iterators. Let's get to it!

Iterator adaptors

Iterator adaptors take an iterator and modify it somehow, producing a new iterator. The simplest one is called map:

(1..100).map(|x| x + 1);

map is called upon another iterator, and produces a new iterator where each element reference has the closure it's been given as an argument called on it. So this would give us the numbers from 2-100. Well, almost! If you compile the example, you'll get a warning:

warning: unused result which must be used: iterator adaptors are lazy and
         do nothing unless consumed, #[warn(unused_must_use)] on by default
(1..100).map(|x| x + 1);
 ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Laziness strikes again! That closure will never execute. This example doesn't print any numbers:

(1..100).map(|x| println!("{}", x));

If you are trying to execute a closure on an iterator for its side effects, just use for instead.

There are tons of interesting iterator adaptors. take(n) will return an iterator over the next n elements of the original iterator. Let's try it out with an infinite iterator:

for i in (1..).take(5) {
    println!("{}", i);
}

This will print

1
2
3
4
5

filter() is an adapter that takes a closure as an argument. This closure returns true or false. The new iterator filter() produces only the elements that the closure returns true for:

for i in (1..100).filter(|&x| x % 2 == 0) {
    println!("{}", i);
}

This will print all of the even numbers between one and a hundred. (Note that because filter doesn't consume the elements that are being iterated over, it is passed a reference to each element, and thus the filter predicate uses the &x pattern to extract the integer itself.)

You can chain all three things together: start with an iterator, adapt it a few times, and then consume the result. Check it out:

(1..)
    .filter(|&x| x % 2 == 0)
    .filter(|&x| x % 3 == 0)
    .take(5)
    .collect::<Vec<i32>>();

This will give you a vector containing 6, 12, 18, 24, and 30.

This is just a small taste of what iterators, iterator adaptors, and consumers can help you with. There are a number of really useful iterators, and you can write your own as well. Iterators provide a safe, efficient way to manipulate all kinds of lists. They're a little unusual at first, but if you play with them, you'll get hooked. For a full list of the different iterators and consumers, check out the iterator module documentation.

I/O

Read & Write

std::fs

std::path

std::env

Testing

Program testing can be a very effective way to show the presence of bugs, but it is hopelessly inadequate for showing their absence.

Edsger W. Dijkstra, "The Humble Programmer" (1972)

Let's talk about how to test Rust code. What we will not be talking about is the right way to test Rust code. There are many schools of thought regarding the right and wrong way to write tests. All of these approaches use the same basic tools, and so we'll show you the syntax for using them.

The test attribute

At its simplest, a test in Rust is a function that's annotated with the test attribute. Let's make a new project with Cargo called adder:

$ cargo new adder
$ cd adder

Cargo will automatically generate a simple test when you make a new project. Here's the contents of src/lib.rs:

#[test]
fn it_works() {
}

Note the #[test]. This attribute indicates that this is a test function. It currently has no body. That's good enough to pass! We can run the tests with cargo test:

$ cargo test
   Compiling adder v0.0.1 (file:///home/you/projects/adder)
     Running target/adder-91b3e234d4ed382a

running 1 test
test it_works ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured

   Doc-tests adder

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured

Cargo compiled and ran our tests. There are two sets of output here: one for the test we wrote, and another for documentation tests. We'll talk about those later. For now, see this line:

test it_works ... ok

Note the it_works. This comes from the name of our function:

fn it_works() {
# }

We also get a summary line:

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured

So why does our do-nothing test pass? Any test which doesn't panic! passes, and any test that does panic! fails. Let's make our test fail:

#[test]
fn it_works() {
    assert!(false);
}

assert! is a macro provided by Rust which takes one argument: if the argument is true, nothing happens. If the argument is false, it panic!s. Let's run our tests again:

$ cargo test
   Compiling adder v0.0.1 (file:///home/you/projects/adder)
     Running target/adder-91b3e234d4ed382a

running 1 test
test it_works ... FAILED

failures:

---- it_works stdout ----
        thread 'it_works' panicked at 'assertion failed: false', /home/steve/tmp/adder/src/lib.rs:3



failures:
    it_works

test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured

thread '<main>' panicked at 'Some tests failed', /home/steve/src/rust/src/libtest/lib.rs:247

Rust indicates that our test failed:

test it_works ... FAILED

And that's reflected in the summary line:

test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured

We also get a non-zero status code. We can use $? on OS X and Linux:

$ echo $?
101

On Windows, if you’re using cmd:

> echo %ERRORLEVEL%

And if you’re using PowerShell:

> echo $LASTEXITCODE # the code itself
> echo $? # a boolean, fail or succeed

This is useful if you want to integrate cargo test into other tooling.

We can invert our test's failure with another attribute: should_panic:

#[test]
#[should_panic]
fn it_works() {
    assert!(false);
}

This test will now succeed if we panic! and fail if we complete. Let's try it:

$ cargo test
   Compiling adder v0.0.1 (file:///home/you/projects/adder)
     Running target/adder-91b3e234d4ed382a

running 1 test
test it_works ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured

   Doc-tests adder

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured

Rust provides another macro, assert_eq!, that compares two arguments for equality:

#[test]
#[should_panic]
fn it_works() {
    assert_eq!("Hello", "world");
}

Does this test pass or fail? Because of the should_panic attribute, it passes:

$ cargo test
   Compiling adder v0.0.1 (file:///home/you/projects/adder)
     Running target/adder-91b3e234d4ed382a

running 1 test
test it_works ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured

   Doc-tests adder

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured

should_panic tests can be fragile, as it's hard to guarantee that the test didn't fail for an unexpected reason. To help with this, an optional expected parameter can be added to the should_panic attribute. The test harness will make sure that the failure message contains the provided text. A safer version of the example above would be:

#[test]
#[should_panic(expected = "assertion failed")]
fn it_works() {
    assert_eq!("Hello", "world");
}

That's all there is to the basics! Let's write one 'real' test:

pub fn add_two(a: i32) -> i32 {
    a + 2
}

#[test]
fn it_works() {
    assert_eq!(4, add_two(2));
}

This is a very common use of assert_eq!: call some function with some known arguments and compare it to the expected output.

The ignore attribute

Sometimes a few specific tests can be very time-consuming to execute. These can be disabled by default by using the ignore attribute:

#[test]
fn it_works() {
    assert_eq!(4, add_two(2));
}

#[test]
#[ignore]
fn expensive_test() {
    // code that takes an hour to run
}

Now we run our tests and see that it_works is run, but expensive_test is not:

$ cargo test
   Compiling adder v0.0.1 (file:///home/you/projects/adder)
     Running target/adder-91b3e234d4ed382a

running 2 tests
test expensive_test ... ignored
test it_works ... ok

test result: ok. 1 passed; 0 failed; 1 ignored; 0 measured

   Doc-tests adder

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured

The expensive tests can be run explicitly using cargo test -- --ignored:

$ cargo test -- --ignored
     Running target/adder-91b3e234d4ed382a

running 1 test
test expensive_test ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured

   Doc-tests adder

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured

The --ignored argument is an argument to the test binary, and not to Cargo, which is why the command is cargo test -- --ignored.

The tests module

There is one way in which our existing example is not idiomatic: it's missing the tests module. The idiomatic way of writing our example looks like this:

pub fn add_two(a: i32) -> i32 {
    a + 2
}

#[cfg(test)]
mod tests {
    use super::add_two;

    #[test]
    fn it_works() {
        assert_eq!(4, add_two(2));
    }
}

There's a few changes here. The first is the introduction of a mod tests with a cfg attribute. The module allows us to group all of our tests together, and to also define helper functions if needed, that don't become a part of the rest of our crate. The cfg attribute only compiles our test code if we're currently trying to run the tests. This can save compile time, and also ensures that our tests are entirely left out of a normal build.

The second change is the use declaration. Because we're in an inner module, we need to bring our test function into scope. This can be annoying if you have a large module, and so this is a common use of globs. Let's change our src/lib.rs to make use of it:

pub fn add_two(a: i32) -> i32 {
    a + 2
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn it_works() {
        assert_eq!(4, add_two(2));
    }
}

Note the different use line. Now we run our tests:

$ cargo test
    Updating registry `https://github.com/rust-lang/crates.io-index`
   Compiling adder v0.0.1 (file:///home/you/projects/adder)
     Running target/adder-91b3e234d4ed382a

running 1 test
test tests::it_works ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured

   Doc-tests adder

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured

It works!

The current convention is to use the tests module to hold your "unit-style" tests. Anything that just tests one small bit of functionality makes sense to go here. But what about "integration-style" tests instead? For that, we have the tests directory.

The tests directory

To write an integration test, let's make a tests directory, and put a tests/lib.rs file inside, with this as its contents:

extern crate adder;

#[test]
fn it_works() {
    assert_eq!(4, adder::add_two(2));
}

This looks similar to our previous tests, but slightly different. We now have an extern crate adder at the top. This is because the tests in the tests directory are an entirely separate crate, and so we need to import our library. This is also why tests is a suitable place to write integration-style tests: they use the library like any other consumer of it would.

Let's run them:

$ cargo test
   Compiling adder v0.0.1 (file:///home/you/projects/adder)
     Running target/adder-91b3e234d4ed382a

running 1 test
test tests::it_works ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured

     Running target/lib-c18e7d3494509e74

running 1 test
test it_works ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured

   Doc-tests adder

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured

Now we have three sections: our previous test is also run, as well as our new one.

That's all there is to the tests directory. The tests module isn't needed here, since the whole thing is focused on tests.

Let's finally check out that third section: documentation tests.

Documentation tests

Nothing is better than documentation with examples. Nothing is worse than examples that don't actually work, because the code has changed since the documentation has been written. To this end, Rust supports automatically running examples in your documentation (note: this only works in library crates, not binary crates). Here's a fleshed-out src/lib.rs with examples:

//! The `adder` crate provides functions that add numbers to other numbers.
//!
//! # Examples
//!
//! ```
//! assert_eq!(4, adder::add_two(2));
//! ```

/// This function adds two to its argument.
///
/// # Examples
///
/// ```
/// use adder::add_two;
///
/// assert_eq!(4, add_two(2));
/// ```
pub fn add_two(a: i32) -> i32 {
    a + 2
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn it_works() {
        assert_eq!(4, add_two(2));
    }
}

Note the module-level documentation with //! and the function-level documentation with ///. Rust's documentation supports Markdown in comments, and so triple graves mark code blocks. It is conventional to include the # Examples section, exactly like that, with examples following.

Let's run the tests again:

$ cargo test
   Compiling adder v0.0.1 (file:///home/steve/tmp/adder)
     Running target/adder-91b3e234d4ed382a

running 1 test
test tests::it_works ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured

     Running target/lib-c18e7d3494509e74

running 1 test
test it_works ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured

   Doc-tests adder

running 2 tests
test add_two_0 ... ok
test _0 ... ok

test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured

Now we have all three kinds of tests running! Note the names of the documentation tests: the _0 is generated for the module test, and add_two_0 for the function test. These will auto increment with names like add_two_1 as you add more examples.

We haven’t covered all of the details with writing documentation tests. For more, please see the Documentation chapter

One final note: documentation tests cannot be run on binary crates. To see more on file arrangement see the Crates and Modules section.

Smart Pointers

Deref

Deref coercions

Box<T>

Rc<T>

Concurrency

Threads

Send & Sync

Arc<T>

Mutex<T>

Channels

Unsafe

Rust’s main draw is its powerful static guarantees about behavior. But safety checks are conservative by nature: there are some programs that are actually safe, but the compiler is not able to verify this is true. To write these kinds of programs, we need to tell the compiler to relax its restrictions a bit. For this, Rust has a keyword, unsafe. Code using unsafe has less restrictions than normal code does.

Let’s go over the syntax, and then we’ll talk semantics. unsafe is used in four contexts. The first one is to mark a function as unsafe:

unsafe fn danger_will_robinson() {
    // scary stuff
}

All functions called from FFI must be marked as unsafe, for example. The second use of unsafe is an unsafe block:

unsafe {
    // scary stuff
}

The third is for unsafe traits:

unsafe trait Scary { }

And the fourth is for implementing one of those traits:

# unsafe trait Scary { }
unsafe impl Scary for i32 {}

It’s important to be able to explicitly delineate code that may have bugs that cause big problems. If a Rust program segfaults, you can be sure it’s somewhere in the sections marked unsafe.

What does ‘safe’ mean?

Safe, in the context of Rust, means ‘doesn’t do anything unsafe’. It’s also important to know that there are certain behaviors that are probably not desirable in your code, but are expressly not unsafe:

  • Deadlocks
  • Leaks of memory or other resources
  • Exiting without calling destructors
  • Integer overflow

Rust cannot prevent all kinds of software problems. Buggy code can and will be written in Rust. These things aren’t great, but they don’t qualify as unsafe specifically.

In addition, the following are all undefined behaviors in Rust, and must be avoided, even when writing unsafe code:

  • Data races
  • Dereferencing a null/dangling raw pointer
  • Reads of undef (uninitialized) memory
  • Breaking the pointer aliasing rules with raw pointers.
  • &mut T and &T follow LLVM’s scoped noalias model, except if the &T contains an UnsafeCell<U>. Unsafe code must not violate these aliasing guarantees.
  • Mutating an immutable value/reference without UnsafeCell<U>
  • Invoking undefined behavior via compiler intrinsics:
    • Indexing outside of the bounds of an object with std::ptr::offset (offset intrinsic), with the exception of one byte past the end which is permitted.
    • Using std::ptr::copy_nonoverlapping_memory (memcpy32/memcpy64 intrinsics) on overlapping buffers
  • Invalid values in primitive types, even in private fields/locals:
    • Null/dangling references or boxes
    • A value other than false (0) or true (1) in a bool
    • A discriminant in an enum not included in its type definition
    • A value in a char which is a surrogate or above char::MAX
    • Non-UTF-8 byte sequences in a str
  • Unwinding into Rust from foreign code or unwinding from Rust into foreign code.

Unsafe Superpowers

In both unsafe functions and unsafe blocks, Rust will let you do three things that you normally can not do. Just three. Here they are:

  1. Access or update a static mutable variable.
  2. Dereference a raw pointer.
  3. Call unsafe functions. This is the most powerful ability.

That’s it. It’s important that unsafe does not, for example, ‘turn off the borrow checker’. Adding unsafe to some random Rust code doesn’t change its semantics, it won’t just start accepting anything. But it will let you write things that do break some of the rules.

You will also encounter the unsafe keyword when writing bindings to foreign (non-Rust) interfaces. You're encouraged to write a safe, native Rust interface around the methods provided by the library.

Let’s go over the basic three abilities listed, in order.

Access or update a static mut

Rust has a feature called ‘static mut’ which allows for mutable global state. Doing so can cause a data race, and as such is inherently not safe. For more details, see the static section of the book.

Dereference a raw pointer

Raw pointers let you do arbitrary pointer arithmetic, and can cause a number of different memory safety and security issues. In some senses, the ability to dereference an arbitrary pointer is one of the most dangerous things you can do. For more on raw pointers, see their section of the book.

Call unsafe functions

This last ability works with both aspects of unsafe: you can only call functions marked unsafe from inside an unsafe block.

This ability is powerful and varied. Rust exposes some compiler intrinsics as unsafe functions, and some unsafe functions bypass safety checks, trading safety for speed.

I’ll repeat again: even though you can do arbitrary things in unsafe blocks and functions doesn’t mean you should. The compiler will act as though you’re upholding its invariants, so be careful!

Raw Pointers

Rust has a number of different smart pointer types in its standard library, but there are two types that are extra-special. Much of Rust’s safety comes from compile-time checks, but raw pointers don’t have such guarantees, and are unsafe to use.

*const T and *mut T are called ‘raw pointers’ in Rust. Sometimes, when writing certain kinds of libraries, you’ll need to get around Rust’s safety guarantees for some reason. In this case, you can use raw pointers to implement your library, while exposing a safe interface for your users. For example, * pointers are allowed to alias, allowing them to be used to write shared-ownership types, and even thread-safe shared memory types (the Rc<T> and Arc<T> types are both implemented entirely in Rust).

Here are some things to remember about raw pointers that are different than other pointer types. They:

  • are not guaranteed to point to valid memory and are not even guaranteed to be non-null (unlike both Box and &);
  • do not have any automatic clean-up, unlike Box, and so require manual resource management;
  • are plain-old-data, that is, they don't move ownership, again unlike Box, hence the Rust compiler cannot protect against bugs like use-after-free;
  • lack any form of lifetimes, unlike &, and so the compiler cannot reason about dangling pointers; and
  • have no guarantees about aliasing or mutability other than mutation not being allowed directly through a *const T.

Basics

Creating a raw pointer is perfectly safe:

let x = 5;
let raw = &x as *const i32;

let mut y = 10;
let raw_mut = &mut y as *mut i32;

However, dereferencing one is not. This won’t work:

let x = 5;
let raw = &x as *const i32;

println!("raw points at {}", *raw);

It gives this error:

error: dereference of raw pointer requires unsafe function or block [E0133]
     println!("raw points at {}", *raw);
                                  ^~~~

When you dereference a raw pointer, you’re taking responsibility that it’s not pointing somewhere that would be incorrect. As such, you need unsafe:

let x = 5;
let raw = &x as *const i32;

let points_at = unsafe { *raw };

println!("raw points at {}", points_at);

For more operations on raw pointers, see their API documentation.

FFI

Raw pointers are useful for FFI: Rust’s *const T and *mut T are similar to C’s const T* and T*, respectively. For more about this use, consult the FFI chapter.

References and raw pointers

At runtime, a raw pointer * and a reference pointing to the same piece of data have an identical representation. In fact, an &T reference will implicitly coerce to an *const T raw pointer in safe code and similarly for the mut variants (both coercions can be performed explicitly with, respectively, value as *const T and value as *mut T).

Going the opposite direction, from *const to a reference &, is not safe. A &T is always valid, and so, at a minimum, the raw pointer *const T has to point to a valid instance of type T. Furthermore, the resulting pointer must satisfy the aliasing and mutability laws of references. The compiler assumes these properties are true for any references, no matter how they are created, and so any conversion from raw pointers is asserting that they hold. The programmer must guarantee this.

The recommended method for the conversion is:

// explicit cast
let i: u32 = 1;
let p_imm: *const u32 = &i as *const u32;

// implicit coercion
let mut m: u32 = 2;
let p_mut: *mut u32 = &mut m;

unsafe {
    let ref_imm: &u32 = &*p_imm;
    let ref_mut: &mut u32 = &mut *p_mut;
}

The &*x dereferencing style is preferred to using a transmute. The latter is far more powerful than necessary, and the more restricted operation is harder to use incorrectly; for example, it requires that x is a pointer (unlike transmute).

transmute

FFI

Conditional Compilation

Rust has a special attribute, #[cfg], which allows you to compile code based on a flag passed to the compiler. It has two forms:

#[cfg(foo)]
# fn foo() {}

#[cfg(bar = "baz")]
# fn bar() {}

They also have some helpers:

#[cfg(any(unix, windows))]
# fn foo() {}

#[cfg(all(unix, target_pointer_width = "32"))]
# fn bar() {}

#[cfg(not(foo))]
# fn not_foo() {}

These can nest arbitrarily:

#[cfg(any(not(unix), all(target_os="macos", target_arch = "powerpc")))]
# fn foo() {}

As for how to enable or disable these switches, if you’re using Cargo, they get set in the [features] section of your Cargo.toml:

[features]
# no features by default
default = []

# The “secure-password” feature depends on the bcrypt package.
secure-password = ["bcrypt"]

When you do this, Cargo passes along a flag to rustc:

--cfg feature="${feature_name}"

The sum of these cfg flags will determine which ones get activated, and therefore, which code gets compiled. Let’s take this code:

#[cfg(feature = "foo")]
mod foo {
}

If we compile it with cargo build --features "foo", it will send the --cfg feature="foo" flag to rustc, and the output will have the mod foo in it. If we compile it with a regular cargo build, no extra flags get passed on, and so, no foo module will exist.

cfg_attr

You can also set another attribute based on a cfg variable with cfg_attr:

#[cfg_attr(a, b)]
# fn foo() {}

Will be the same as #[b] if a is set by cfg attribute, and nothing otherwise.

cfg!

The cfg! syntax extension lets you use these kinds of flags elsewhere in your code, too:

if cfg!(target_os = "macos") || cfg!(target_os = "ios") {
    println!("Think Different!");
}

These will be replaced by a true or false at compile-time, depending on the configuration settings.

Bindings to C

Using Rust From Other Languages

For our third project, we’re going to choose something that shows off one of Rust’s greatest strengths: a lack of a substantial runtime.

As organizations grow, they increasingly rely on a multitude of programming languages. Different programming languages have different strengths and weaknesses, and a polyglot stack lets you use a particular language where its strengths make sense and a different one where it’s weak.

A very common area where many programming languages are weak is in runtime performance of programs. Often, using a language that is slower, but offers greater programmer productivity, is a worthwhile trade-off. To help mitigate this, they provide a way to write some of your system in C and then call that C code as though it were written in the higher-level language. This is called a ‘foreign function interface’, often shortened to ‘FFI’.

Rust has support for FFI in both directions: it can call into C code easily, but crucially, it can also be called into as easily as C. Combined with Rust’s lack of a garbage collector and low runtime requirements, this makes Rust a great candidate to embed inside of other languages when you need that extra oomph.

There is a whole chapter devoted to FFI and its specifics elsewhere in the book, but in this chapter, we’ll examine this particular use-case of FFI, with examples in Ruby, Python, and JavaScript.

The problem

There are many different projects we could choose here, but we’re going to pick an example where Rust has a clear advantage over many other languages: numeric computing and threading.

Many languages, for the sake of consistency, place numbers on the heap, rather than on the stack. Especially in languages that focus on object-oriented programming and use garbage collection, heap allocation is the default. Sometimes optimizations can stack allocate particular numbers, but rather than relying on an optimizer to do its job, we may want to ensure that we’re always using primitive number types rather than some sort of object type.

Second, many languages have a ‘global interpreter lock’ (GIL), which limits concurrency in many situations. This is done in the name of safety, which is a positive effect, but it limits the amount of work that can be done at the same time, which is a big negative.

To emphasize these two aspects, we’re going to create a little project that uses these two aspects heavily. Since the focus of the example is to embed Rust into other languages, rather than the problem itself, we’ll just use a toy example:

Start ten threads. Inside each thread, count from one to five million. After all ten threads are finished, print out ‘done!’.

I chose five million based on my particular computer. Here’s an example of this code in Ruby:

threads = []

10.times do
  threads << Thread.new do
    count = 0

    5_000_000.times do
      count += 1
    end

    count
  end
end

threads.each do |t|
  puts "Thread finished with count=#{t.value}"
end
puts "done!"

Try running this example, and choose a number that runs for a few seconds. Depending on your computer’s hardware, you may have to increase or decrease the number.

On my system, running this program takes 2.156 seconds. And, if I use some sort of process monitoring tool, like top, I can see that it only uses one core on my machine. That’s the GIL kicking in.

While it’s true that this is a synthetic program, one can imagine many problems that are similar to this in the real world. For our purposes, spinning up a few busy threads represents some sort of parallel, expensive computation.

A Rust library

Let’s rewrite this problem in Rust. First, let’s make a new project with Cargo:

$ cargo new embed
$ cd embed

This program is fairly easy to write in Rust:

use std::thread;

fn process() {
    let handles: Vec<_> = (0..10).map(|_| {
        thread::spawn(|| {
            let mut x = 0;
            for _ in 0..5_000_000 {
                x += 1
            }
            x
        })
    }).collect();

    for h in handles {
        println!("Thread finished with count={}",
        h.join().map_err(|_| "Could not join a thread!").unwrap());
    }
}

Some of this should look familiar from previous examples. We spin up ten threads, collecting them into a handles vector. Inside of each thread, we loop five million times, and add one to x each time. Finally, we join on each thread.

Right now, however, this is a Rust library, and it doesn’t expose anything that’s callable from C. If we tried to hook this up to another language right now, it wouldn’t work. We only need to make two small changes to fix this, though. The first is to modify the beginning of our code:

#[no_mangle]
pub extern fn process() {

We have to add a new attribute, no_mangle. When you create a Rust library, it changes the name of the function in the compiled output. The reasons for this are outside the scope of this tutorial, but in order for other languages to know how to call the function, we can’t do that. This attribute turns that behavior off.

The other change is the pub extern. The pub means that this function should be callable from outside of this module, and the extern says that it should be able to be called from C. That’s it! Not a whole lot of change.

The second thing we need to do is to change a setting in our Cargo.toml. Add this at the bottom:

[lib]
name = "embed"
crate-type = ["dylib"]

This tells Rust that we want to compile our library into a standard dynamic library. By default, Rust compiles an ‘rlib’, a Rust-specific format.

Let’s build the project now:

$ cargo build --release
   Compiling embed v0.1.0 (file:///home/steve/src/embed)

We’ve chosen cargo build --release, which builds with optimizations on. We want this to be as fast as possible! You can find the output of the library in target/release:

$ ls target/release/
build  deps  examples  libembed.so  native

That libembed.so is our ‘shared object’ library. We can use this file just like any shared object library written in C! As an aside, this may be embed.dll (Microsoft Windows) or libembed.dylib (Mac OS X), depending on your operating system.

Now that we’ve got our Rust library built, let’s use it from our Ruby.

Ruby

Open up an embed.rb file inside of our project, and do this:

require 'ffi'

module Hello
  extend FFI::Library
  ffi_lib 'target/release/libembed.so'
  attach_function :process, [], :void
end

Hello.process

puts 'done!'

Before we can run this, we need to install the ffi gem:

$ gem install ffi # this may need sudo
Fetching: ffi-1.9.8.gem (100%)
Building native extensions.  This could take a while...
Successfully installed ffi-1.9.8
Parsing documentation for ffi-1.9.8
Installing ri documentation for ffi-1.9.8
Done installing documentation for ffi after 0 seconds
1 gem installed

And finally, we can try running it:

$ ruby embed.rb
Thread finished with count=5000000
Thread finished with count=5000000
Thread finished with count=5000000
Thread finished with count=5000000
Thread finished with count=5000000
Thread finished with count=5000000
Thread finished with count=5000000
Thread finished with count=5000000
Thread finished with count=5000000
Thread finished with count=5000000
done!
done!
$

Whoa, that was fast! On my system, this took 0.086 seconds, rather than the two seconds the pure Ruby version took. Let’s break down this Ruby code:

require 'ffi'

We first need to require the ffi gem. This lets us interface with our Rust library like a C library.

module Hello
  extend FFI::Library
  ffi_lib 'target/release/libembed.so'

The Hello module is used to attach the native functions from the shared library. Inside, we extend the necessary FFI::Library module and then call ffi_lib to load up our shared object library. We just pass it the path that our library is stored, which, as we saw before, is target/release/libembed.so.

attach_function :process, [], :void

The attach_function method is provided by the FFI gem. It’s what connects our process() function in Rust to a Ruby function of the same name. Since process() takes no arguments, the second parameter is an empty array, and since it returns nothing, we pass :void as the final argument.

Hello.process

This is the actual call into Rust. The combination of our module and the call to attach_function sets this all up. It looks like a Ruby function but is actually Rust!

puts 'done!'

Finally, as per our project’s requirements, we print out done!.

That’s it! As we’ve seen, bridging between the two languages is really easy, and buys us a lot of performance.

Next, let’s try Python!

Python

Create an embed.py file in this directory, and put this in it:

from ctypes import cdll

lib = cdll.LoadLibrary("target/release/libembed.so")

lib.process()

print("done!")

Even easier! We use cdll from the ctypes module. A quick call to LoadLibrary later, and we can call process().

On my system, this takes 0.017 seconds. Speedy!

Node.js

Node isn’t a language, but it’s currently the dominant implementation of server-side JavaScript.

In order to do FFI with Node, we first need to install the library:

$ npm install ffi

After that installs, we can use it:

var ffi = require('ffi');

var lib = ffi.Library('target/release/libembed', {
  'process': ['void', []]
});

lib.process();

console.log("done!");

It looks more like the Ruby example than the Python example. We use the ffi module to get access to ffi.Library(), which loads up our shared object. We need to annotate the return type and argument types of the function, which are void for return and an empty array to signify no arguments. From there, we just call it and print the result.

On my system, this takes a quick 0.092 seconds.

Conclusion

As you can see, the basics of doing this are very easy. Of course, there's a lot more that we could do here. Check out the FFI chapter for more details.

static

Cargo

Crates.io

Advanced Type System Features

Associated Types

Associated types are a powerful part of Rust’s type system. They’re related to the idea of a ‘type family’, in other words, grouping multiple types together. That description is a bit abstract, so let’s dive right into an example. If you want to write a Graph trait, you have two types to be generic over: the node type and the edge type. So you might write a trait, Graph<N, E>, that looks like this:

trait Graph<N, E> {
    fn has_edge(&self, &N, &N) -> bool;
    fn edges(&self, &N) -> Vec<E>;
    // etc
}

While this sort of works, it ends up being awkward. For example, any function that wants to take a Graph as a parameter now also needs to be generic over the Node and Edge types too:

fn distance<N, E, G: Graph<N, E>>(graph: &G, start: &N, end: &N) -> u32 { ... }

Our distance calculation works regardless of our Edge type, so the E stuff in this signature is just a distraction.

What we really want to say is that a certain Edge and Node type come together to form each kind of Graph. We can do that with associated types:

trait Graph {
    type N;
    type E;

    fn has_edge(&self, &Self::N, &Self::N) -> bool;
    fn edges(&self, &Self::N) -> Vec<Self::E>;
    // etc
}

Now, our clients can be abstract over a given Graph:

fn distance<G: Graph>(graph: &G, start: &G::N, end: &G::N) -> u32 { ... }

No need to deal with the Edge type here!

Let’s go over all this in more detail.

Defining associated types

Let’s build that Graph trait. Here’s the definition:

trait Graph {
    type N;
    type E;

    fn has_edge(&self, &Self::N, &Self::N) -> bool;
    fn edges(&self, &Self::N) -> Vec<Self::E>;
}

Simple enough. Associated types use the type keyword, and go inside the body of the trait, with the functions.

These type declarations can have all the same thing as functions do. For example, if we wanted our N type to implement Display, so we can print the nodes out, we could do this:

use std::fmt;

trait Graph {
    type N: fmt::Display;
    type E;

    fn has_edge(&self, &Self::N, &Self::N) -> bool;
    fn edges(&self, &Self::N) -> Vec<Self::E>;
}

Implementing associated types

Just like any trait, traits that use associated types use the impl keyword to provide implementations. Here’s a simple implementation of Graph:

# trait Graph {
#     type N;
#     type E;
#     fn has_edge(&self, &Self::N, &Self::N) -> bool;
#     fn edges(&self, &Self::N) -> Vec<Self::E>;
# }
struct Node;

struct Edge;

struct MyGraph;

impl Graph for MyGraph {
    type N = Node;
    type E = Edge;

    fn has_edge(&self, n1: &Node, n2: &Node) -> bool {
        true
    }

    fn edges(&self, n: &Node) -> Vec<Edge> {
        Vec::new()
    }
}

This silly implementation always returns true and an empty Vec<Edge>, but it gives you an idea of how to implement this kind of thing. We first need three structs, one for the graph, one for the node, and one for the edge. If it made more sense to use a different type, that would work as well, we’re just going to use structs for all three here.

Next is the impl line, which is just like implementing any other trait.

From here, we use = to define our associated types. The name the trait uses goes on the left of the =, and the concrete type we’re implementing this for goes on the right. Finally, we use the concrete types in our function declarations.

Trait objects with associated types

There’s one more bit of syntax we should talk about: trait objects. If you try to create a trait object from an associated type, like this:

# trait Graph {
#     type N;
#     type E;
#     fn has_edge(&self, &Self::N, &Self::N) -> bool;
#     fn edges(&self, &Self::N) -> Vec<Self::E>;
# }
# struct Node;
# struct Edge;
# struct MyGraph;
# impl Graph for MyGraph {
#     type N = Node;
#     type E = Edge;
#     fn has_edge(&self, n1: &Node, n2: &Node) -> bool {
#         true
#     }
#     fn edges(&self, n: &Node) -> Vec<Edge> {
#         Vec::new()
#     }
# }
let graph = MyGraph;
let obj = Box::new(graph) as Box<Graph>;

You’ll get two errors:

error: the value of the associated type `E` (from the trait `main::Graph`) must
be specified [E0191]
let obj = Box::new(graph) as Box<Graph>;
          ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
24:44 error: the value of the associated type `N` (from the trait
`main::Graph`) must be specified [E0191]
let obj = Box::new(graph) as Box<Graph>;
          ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~

We can’t create a trait object like this, because we don’t know the associated types. Instead, we can write this:

# trait Graph {
#     type N;
#     type E;
#     fn has_edge(&self, &Self::N, &Self::N) -> bool;
#     fn edges(&self, &Self::N) -> Vec<Self::E>;
# }
# struct Node;
# struct Edge;
# struct MyGraph;
# impl Graph for MyGraph {
#     type N = Node;
#     type E = Edge;
#     fn has_edge(&self, n1: &Node, n2: &Node) -> bool {
#         true
#     }
#     fn edges(&self, n: &Node) -> Vec<Edge> {
#         Vec::new()
#     }
# }
let graph = MyGraph;
let obj = Box::new(graph) as Box<Graph<N=Node, E=Edge>>;

The N=Node syntax allows us to provide a concrete type, Node, for the N type parameter. Same with E=Edge. If we didn’t provide this constraint, we couldn’t be sure which impl to match this trait object to.

Trait Objects

When code involves polymorphism, there needs to be a mechanism to determine which specific version is actually run. This is called ‘dispatch’. There are two major forms of dispatch: static dispatch and dynamic dispatch. While Rust favors static dispatch, it also supports dynamic dispatch through a mechanism called ‘trait objects’.

Background

For the rest of this chapter, we’ll need a trait and some implementations. Let’s make a simple one, Foo. It has one method that is expected to return a String.

trait Foo {
    fn method(&self) -> String;
}

We’ll also implement this trait for u8 and String:

# trait Foo { fn method(&self) -> String; }
impl Foo for u8 {
    fn method(&self) -> String { format!("u8: {}", *self) }
}

impl Foo for String {
    fn method(&self) -> String { format!("string: {}", *self) }
}

Static dispatch

We can use this trait to perform static dispatch with trait bounds:

# trait Foo { fn method(&self) -> String; }
# impl Foo for u8 { fn method(&self) -> String { format!("u8: {}", *self) } }
# impl Foo for String { fn method(&self) -> String { format!("string: {}", *self) } }
fn do_something<T: Foo>(x: T) {
    x.method();
}

fn main() {
    let x = 5u8;
    let y = "Hello".to_string();

    do_something(x);
    do_something(y);
}

Rust uses ‘monomorphization’ to perform static dispatch here. This means that Rust will create a special version of do_something() for both u8 and String, and then replace the call sites with calls to these specialized functions. In other words, Rust generates something like this:

# trait Foo { fn method(&self) -> String; }
# impl Foo for u8 { fn method(&self) -> String { format!("u8: {}", *self) } }
# impl Foo for String { fn method(&self) -> String { format!("string: {}", *self) } }
fn do_something_u8(x: u8) {
    x.method();
}

fn do_something_string(x: String) {
    x.method();
}

fn main() {
    let x = 5u8;
    let y = "Hello".to_string();

    do_something_u8(x);
    do_something_string(y);
}

This has a great upside: static dispatch allows function calls to be inlined because the callee is known at compile time, and inlining is the key to good optimization. Static dispatch is fast, but it comes at a tradeoff: ‘code bloat’, due to many copies of the same function existing in the binary, one for each type.

Furthermore, compilers aren’t perfect and may “optimize” code to become slower. For example, functions inlined too eagerly will bloat the instruction cache (cache rules everything around us). This is part of the reason that #[inline] and #[inline(always)] should be used carefully, and one reason why using a dynamic dispatch is sometimes more efficient.

However, the common case is that it is more efficient to use static dispatch, and one can always have a thin statically-dispatched wrapper function that does a dynamic dispatch, but not vice versa, meaning static calls are more flexible. The standard library tries to be statically dispatched where possible for this reason.

Dynamic dispatch

Rust provides dynamic dispatch through a feature called ‘trait objects’. Trait objects, like &Foo or Box<Foo>, are normal values that store a value of any type that implements the given trait, where the precise type can only be known at runtime.

A trait object can be obtained from a pointer to a concrete type that implements the trait by casting it (e.g. &x as &Foo) or coercing it (e.g. using &x as an argument to a function that takes &Foo).

These trait object coercions and casts also work for pointers like &mut T to &mut Foo and Box<T> to Box<Foo>, but that’s all at the moment. Coercions and casts are identical.

This operation can be seen as ‘erasing’ the compiler’s knowledge about the specific type of the pointer, and hence trait objects are sometimes referred to as ‘type erasure’.

Coming back to the example above, we can use the same trait to perform dynamic dispatch with trait objects by casting:

# trait Foo { fn method(&self) -> String; }
# impl Foo for u8 { fn method(&self) -> String { format!("u8: {}", *self) } }
# impl Foo for String { fn method(&self) -> String { format!("string: {}", *self) } }

fn do_something(x: &Foo) {
    x.method();
}

fn main() {
    let x = 5u8;
    do_something(&x as &Foo);
}

or by coercing:

# trait Foo { fn method(&self) -> String; }
# impl Foo for u8 { fn method(&self) -> String { format!("u8: {}", *self) } }
# impl Foo for String { fn method(&self) -> String { format!("string: {}", *self) } }

fn do_something(x: &Foo) {
    x.method();
}

fn main() {
    let x = "Hello".to_string();
    do_something(&x);
}

A function that takes a trait object is not specialized to each of the types that implements Foo: only one copy is generated, often (but not always) resulting in less code bloat. However, this comes at the cost of requiring slower virtual function calls, and effectively inhibiting any chance of inlining and related optimizations from occurring.

Why pointers?

Rust does not put things behind a pointer by default, unlike many managed languages, so types can have different sizes. Knowing the size of the value at compile time is important for things like passing it as an argument to a function, moving it about on the stack and allocating (and deallocating) space on the heap to store it.

For Foo, we would need to have a value that could be at least either a String (24 bytes) or a u8 (1 byte), as well as any other type for which dependent crates may implement Foo (any number of bytes at all). There’s no way to guarantee that this last point can work if the values are stored without a pointer, because those other types can be arbitrarily large.

Putting the value behind a pointer means the size of the value is not relevant when we are tossing a trait object around, only the size of the pointer itself.

Representation

The methods of the trait can be called on a trait object via a special record of function pointers traditionally called a ‘vtable’ (created and managed by the compiler).

Trait objects are both simple and complicated: their core representation and layout is quite straight-forward, but there are some curly error messages and surprising behaviors to discover.

Let’s start simple, with the runtime representation of a trait object. The std::raw module contains structs with layouts that are the same as the complicated built-in types, including trait objects:

# mod foo {
pub struct TraitObject {
    pub data: *mut (),
    pub vtable: *mut (),
}
# }

That is, a trait object like &Foo consists of a ‘data’ pointer and a ‘vtable’ pointer.

The data pointer addresses the data (of some unknown type T) that the trait object is storing, and the vtable pointer points to the vtable (‘virtual method table’) corresponding to the implementation of Foo for T.

A vtable is essentially a struct of function pointers, pointing to the concrete piece of machine code for each method in the implementation. A method call like trait_object.method() will retrieve the correct pointer out of the vtable and then do a dynamic call of it. For example:

struct FooVtable {
    destructor: fn(*mut ()),
    size: usize,
    align: usize,
    method: fn(*const ()) -> String,
}

// u8:

fn call_method_on_u8(x: *const ()) -> String {
    // the compiler guarantees that this function is only called
    // with `x` pointing to a u8
    let byte: &u8 = unsafe { &*(x as *const u8) };

    byte.method()
}

static Foo_for_u8_vtable: FooVtable = FooVtable {
    destructor: /* compiler magic */,
    size: 1,
    align: 1,

    // cast to a function pointer
    method: call_method_on_u8 as fn(*const ()) -> String,
};


// String:

fn call_method_on_String(x: *const ()) -> String {
    // the compiler guarantees that this function is only called
    // with `x` pointing to a String
    let string: &String = unsafe { &*(x as *const String) };

    string.method()
}

static Foo_for_String_vtable: FooVtable = FooVtable {
    destructor: /* compiler magic */,
    // values for a 64-bit computer, halve them for 32-bit ones
    size: 24,
    align: 8,

    method: call_method_on_String as fn(*const ()) -> String,
};

The destructor field in each vtable points to a function that will clean up any resources of the vtable’s type: for u8 it is trivial, but for String it will free the memory. This is necessary for owning trait objects like Box<Foo>, which need to clean-up both the Box allocation as well as the internal type when they go out of scope. The size and align fields store the size of the erased type, and its alignment requirements; these are essentially unused at the moment since the information is embedded in the destructor, but will be used in the future, as trait objects are progressively made more flexible.

Suppose we’ve got some values that implement Foo. The explicit form of construction and use of Foo trait objects might look a bit like (ignoring the type mismatches: they’re all just pointers anyway):

let a: String = "foo".to_string();
let x: u8 = 1;

// let b: &Foo = &a;
let b = TraitObject {
    // store the data
    data: &a,
    // store the methods
    vtable: &Foo_for_String_vtable
};

// let y: &Foo = x;
let y = TraitObject {
    // store the data
    data: &x,
    // store the methods
    vtable: &Foo_for_u8_vtable
};

// b.method();
(b.vtable.method)(b.data);

// y.method();
(y.vtable.method)(y.data);

Object Safety

Not every trait can be used to make a trait object. For example, vectors implement Clone, but if we try to make a trait object:

let v = vec![1, 2, 3];
let o = &v as &Clone;

We get an error:

error: cannot convert to a trait object because trait `core::clone::Clone` is not object-safe [E0038]
let o = &v as &Clone;
        ^~
note: the trait cannot require that `Self : Sized`
let o = &v as &Clone;
        ^~

The error says that Clone is not ‘object-safe’. Only traits that are object-safe can be made into trait objects. A trait is object-safe if both of these are true:

  • the trait does not require that Self: Sized
  • all of its methods are object-safe

So what makes a method object-safe? Each method must require that Self: Sized or all of the following:

  • must not have any type parameters
  • must not use Self

Whew! As we can see, almost all of these rules talk about Self. A good intuition is “except in special circumstances, if your trait’s method uses Self, it is not object-safe.”

Universal Function Call Syntax

Sometimes, functions can have the same names. Consider this code:

trait Foo {
    fn f(&self);
}

trait Bar {
    fn f(&self);
}

struct Baz;

impl Foo for Baz {
    fn f(&self) { println!("Baz’s impl of Foo"); }
}

impl Bar for Baz {
    fn f(&self) { println!("Baz’s impl of Bar"); }
}

let b = Baz;

If we were to try to call b.f(), we’d get an error:

error: multiple applicable methods in scope [E0034]
b.f();
  ^~~
note: candidate #1 is defined in an impl of the trait `main::Foo` for the type
`main::Baz`
    fn f(&self) { println!("Baz’s impl of Foo"); }
    ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
note: candidate #2 is defined in an impl of the trait `main::Bar` for the type
`main::Baz`
    fn f(&self) { println!("Baz’s impl of Bar"); }
    ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

We need a way to disambiguate which method we need. This feature is called ‘universal function call syntax’, and it looks like this:

# trait Foo {
#     fn f(&self);
# }
# trait Bar {
#     fn f(&self);
# }
# struct Baz;
# impl Foo for Baz {
#     fn f(&self) { println!("Baz’s impl of Foo"); }
# }
# impl Bar for Baz {
#     fn f(&self) { println!("Baz’s impl of Bar"); }
# }
# let b = Baz;
Foo::f(&b);
Bar::f(&b);

Let’s break it down.

Foo::
Bar::

These halves of the invocation are the types of the two traits: Foo and Bar. This is what ends up actually doing the disambiguation between the two: Rust calls the one from the trait name you use.

f(&b)

When we call a method like b.f() using method syntax, Rust will automatically borrow b if f() takes &self. In this case, Rust will not, and so we need to pass an explicit &b.

Angle-bracket Form

The form of UFCS we just talked about:

Trait::method(args);

Is a short-hand. There’s an expanded form of this that’s needed in some situations:

<Type as Trait>::method(args);

The <>:: syntax is a means of providing a type hint. The type goes inside the <>s. In this case, the type is Type as Trait, indicating that we want Trait’s version of method to be called here. The as Trait part is optional if it’s not ambiguous. Same with the angle brackets, hence the shorter form.

Here’s an example of using the longer form.

trait Foo {
    fn foo() -> i32;
}

struct Bar;

impl Bar {
    fn foo() -> i32 {
        20
    }
}

impl Foo for Bar {
    fn foo() -> i32 {
        10
    }
}

fn main() {
    assert_eq!(10, <Bar as Foo>::foo());
    assert_eq!(20, Bar::foo());
}

Using the angle bracket syntax lets you call the trait method instead of the inherent one.

Coherence

Interior mutability

Cell<T>

RefCell<T>

Macros

By now you’ve learned about many of the tools Rust provides for abstracting and reusing code. These units of code reuse have a rich semantic structure. For example, functions have a type signature, type parameters have trait bounds, and overloaded functions must belong to a particular trait.

This structure means that Rust’s core abstractions have powerful compile-time correctness checking. But this comes at the price of reduced flexibility. If you visually identify a pattern of repeated code, you may find it’s difficult or cumbersome to express that pattern as a generic function, a trait, or anything else within Rust’s semantics.

Macros allow us to abstract at a syntactic level. A macro invocation is shorthand for an "expanded" syntactic form. This expansion happens early in compilation, before any static checking. As a result, macros can capture many patterns of code reuse that Rust’s core abstractions cannot.

The drawback is that macro-based code can be harder to understand, because fewer of the built-in rules apply. Like an ordinary function, a well-behaved macro can be used without understanding its implementation. However, it can be difficult to design a well-behaved macro! Additionally, compiler errors in macro code are harder to interpret, because they describe problems in the expanded code, not the source-level form that developers use.

These drawbacks make macros something of a "feature of last resort". That’s not to say that macros are bad; they are part of Rust because sometimes they’re needed for truly concise, well-abstracted code. Just keep this tradeoff in mind.

Defining a macro

You may have seen the vec! macro, used to initialize a vector with any number of elements.

let x: Vec<u32> = vec![1, 2, 3];
# assert_eq!(x, [1, 2, 3]);

This can’t be an ordinary function, because it takes any number of arguments. But we can imagine it as syntactic shorthand for

let x: Vec<u32> = {
    let mut temp_vec = Vec::new();
    temp_vec.push(1);
    temp_vec.push(2);
    temp_vec.push(3);
    temp_vec
};
# assert_eq!(x, [1, 2, 3]);

We can implement this shorthand, using a macro: [^actual]

[^actual]: The actual definition of vec! in libcollections differs from the one presented here, for reasons of efficiency and reusability.

macro_rules! vec {
    ( $( $x:expr ),* ) => {
        {
            let mut temp_vec = Vec::new();
            $(
                temp_vec.push($x);
            )*
            temp_vec
        }
    };
}
# fn main() {
#     assert_eq!(vec![1,2,3], [1, 2, 3]);
# }

Whoa, that’s a lot of new syntax! Let’s break it down.

macro_rules! vec { ... }

This says we’re defining a macro named vec, much as fn vec would define a function named vec. In prose, we informally write a macro’s name with an exclamation point, e.g. vec!. The exclamation point is part of the invocation syntax and serves to distinguish a macro from an ordinary function.

Matching

The macro is defined through a series of rules, which are pattern-matching cases. Above, we had

( $( $x:expr ),* ) => { ... };

This is like a match expression arm, but the matching happens on Rust syntax trees, at compile time. The semicolon is optional on the last (here, only) case. The "pattern" on the left-hand side of => is known as a ‘matcher’. These have their own little grammar within the language.

The matcher $x:expr will match any Rust expression, binding that syntax tree to the ‘metavariable’ $x. The identifier expr is a ‘fragment specifier’; the full possibilities are enumerated later in this chapter. Surrounding the matcher with $(...),* will match zero or more expressions, separated by commas.

Aside from the special matcher syntax, any Rust tokens that appear in a matcher must match exactly. For example,

macro_rules! foo {
    (x => $e:expr) => (println!("mode X: {}", $e));
    (y => $e:expr) => (println!("mode Y: {}", $e));
}

fn main() {
    foo!(y => 3);
}

will print

mode Y: 3

With

foo!(z => 3);

we get the compiler error

error: no rules expected the token `z`

Expansion

The right-hand side of a macro rule is ordinary Rust syntax, for the most part. But we can splice in bits of syntax captured by the matcher. From the original example:

$(
    temp_vec.push($x);
)*

Each matched expression $x will produce a single push statement in the macro expansion. The repetition in the expansion proceeds in "lockstep" with repetition in the matcher (more on this in a moment).

Because $x was already declared as matching an expression, we don’t repeat :expr on the right-hand side. Also, we don’t include a separating comma as part of the repetition operator. Instead, we have a terminating semicolon within the repeated block.

Another detail: the vec! macro has two pairs of braces on the right-hand side. They are often combined like so:

macro_rules! foo {
    () => {{
        ...
    }}
}

The outer braces are part of the syntax of macro_rules!. In fact, you can use () or [] instead. They simply delimit the right-hand side as a whole.

The inner braces are part of the expanded syntax. Remember, the vec! macro is used in an expression context. To write an expression with multiple statements, including let-bindings, we use a block. If your macro expands to a single expression, you don’t need this extra layer of braces.

Note that we never declared that the macro produces an expression. In fact, this is not determined until we use the macro as an expression. With care, you can write a macro whose expansion works in several contexts. For example, shorthand for a data type could be valid as either an expression or a pattern.

Repetition

The repetition operator follows two principal rules:

  1. $(...)* walks through one "layer" of repetitions, for all of the $names it contains, in lockstep, and
  2. each $name must be under at least as many $(...)*s as it was matched against. If it is under more, it’ll be duplicated, as appropriate.

This baroque macro illustrates the duplication of variables from outer repetition levels.

macro_rules! o_O {
    (
        $(
            $x:expr; [ $( $y:expr ),* ]
        );*
    ) => {
        &[ $($( $x + $y ),*),* ]
    }
}

fn main() {
    let a: &[i32]
        = o_O!(10; [1, 2, 3];
               20; [4, 5, 6]);

    assert_eq!(a, [11, 12, 13, 24, 25, 26]);
}

That’s most of the matcher syntax. These examples use $(...)*, which is a "zero or more" match. Alternatively you can write $(...)+ for a "one or more" match. Both forms optionally include a separator, which can be any token except + or *.

This system is based on "Macro-by-Example" (PDF link).

Hygiene

Some languages implement macros using simple text substitution, which leads to various problems. For example, this C program prints 13 instead of the expected 25.

#define FIVE_TIMES(x) 5 * x

int main() {
    printf("%d\n", FIVE_TIMES(2 + 3));
    return 0;
}

After expansion we have 5 * 2 + 3, and multiplication has greater precedence than addition. If you’ve used C macros a lot, you probably know the standard idioms for avoiding this problem, as well as five or six others. In Rust, we don’t have to worry about it.

macro_rules! five_times {
    ($x:expr) => (5 * $x);
}

fn main() {
    assert_eq!(25, five_times!(2 + 3));
}

The metavariable $x is parsed as a single expression node, and keeps its place in the syntax tree even after substitution.

Another common problem in macro systems is ‘variable capture’. Here’s a C macro, using a GNU C extension to emulate Rust’s expression blocks.

#define LOG(msg) ({ \
    int state = get_log_state(); \
    if (state > 0) { \
        printf("log(%d): %s\n", state, msg); \
    } \
})

Here’s a simple use case that goes terribly wrong:

const char *state = "reticulating splines";
LOG(state)

This expands to

const char *state = "reticulating splines";
int state = get_log_state();
if (state > 0) {
    printf("log(%d): %s\n", state, state);
}

The second variable named state shadows the first one. This is a problem because the print statement should refer to both of them.

The equivalent Rust macro has the desired behavior.

# fn get_log_state() -> i32 { 3 }
macro_rules! log {
    ($msg:expr) => {{
        let state: i32 = get_log_state();
        if state > 0 {
            println!("log({}): {}", state, $msg);
        }
    }};
}

fn main() {
    let state: &str = "reticulating splines";
    log!(state);
}

This works because Rust has a hygienic macro system. Each macro expansion happens in a distinct ‘syntax context’, and each variable is tagged with the syntax context where it was introduced. It’s as though the variable state inside main is painted a different "color" from the variable state inside the macro, and therefore they don’t conflict.

This also restricts the ability of macros to introduce new bindings at the invocation site. Code such as the following will not work:

macro_rules! foo {
    () => (let x = 3);
}

fn main() {
    foo!();
    println!("{}", x);
}

Instead you need to pass the variable name into the invocation, so it’s tagged with the right syntax context.

macro_rules! foo {
    ($v:ident) => (let $v = 3);
}

fn main() {
    foo!(x);
    println!("{}", x);
}

This holds for let bindings and loop labels, but not for items. So the following code does compile:

macro_rules! foo {
    () => (fn x() { });
}

fn main() {
    foo!();
    x();
}

Recursive macros

A macro’s expansion can include more macro invocations, including invocations of the very same macro being expanded. These recursive macros are useful for processing tree-structured input, as illustrated by this (simplistic) HTML shorthand:

# #![allow(unused_must_use)]
macro_rules! write_html {
    ($w:expr, ) => (());

    ($w:expr, $e:tt) => (write!($w, "{}", $e));

    ($w:expr, $tag:ident [ $($inner:tt)* ] $($rest:tt)*) => {{
        write!($w, "<{}>", stringify!($tag));
        write_html!($w, $($inner)*);
        write!($w, "</{}>", stringify!($tag));
        write_html!($w, $($rest)*);
    }};
}

fn main() {
#   // FIXME(#21826)
    use std::fmt::Write;
    let mut out = String::new();

    write_html!(&mut out,
        html[
            head[title["Macros guide"]]
            body[h1["Macros are the best!"]]
        ]);

    assert_eq!(out,
        "<html><head><title>Macros guide</title></head>\
         <body><h1>Macros are the best!</h1></body></html>");
}

Debugging macro code

To see the results of expanding macros, run rustc --pretty expanded. The output represents a whole crate, so you can also feed it back in to rustc, which will sometimes produce better error messages than the original compilation. Note that the --pretty expanded output may have a different meaning if multiple variables of the same name (but different syntax contexts) are in play in the same scope. In this case --pretty expanded,hygiene will tell you about the syntax contexts.

rustc provides two syntax extensions that help with macro debugging. For now, they are unstable and require feature gates.

  • log_syntax!(...) will print its arguments to standard output, at compile time, and "expand" to nothing.

  • trace_macros!(true) will enable a compiler message every time a macro is expanded. Use trace_macros!(false) later in expansion to turn it off.

Syntactic requirements

Even when Rust code contains un-expanded macros, it can be parsed as a full syntax tree. This property can be very useful for editors and other tools that process code. It also has a few consequences for the design of Rust’s macro system.

One consequence is that Rust must determine, when it parses a macro invocation, whether the macro stands in for

  • zero or more items,
  • zero or more methods,
  • an expression,
  • a statement, or
  • a pattern.

A macro invocation within a block could stand for some items, or for an expression / statement. Rust uses a simple rule to resolve this ambiguity. A macro invocation that stands for items must be either

  • delimited by curly braces, e.g. foo! { ... }, or
  • terminated by a semicolon, e.g. foo!(...);

Another consequence of pre-expansion parsing is that the macro invocation must consist of valid Rust tokens. Furthermore, parentheses, brackets, and braces must be balanced within a macro invocation. For example, foo!([) is forbidden. This allows Rust to know where the macro invocation ends.

More formally, the macro invocation body must be a sequence of ‘token trees’. A token tree is defined recursively as either

  • a sequence of token trees surrounded by matching (), [], or {}, or
  • any other single token.

Within a matcher, each metavariable has a ‘fragment specifier’, identifying which syntactic form it matches.

  • ident: an identifier. Examples: x; foo.
  • path: a qualified name. Example: T::SpecialA.
  • expr: an expression. Examples: 2 + 2; if true { 1 } else { 2 }; f(42).
  • ty: a type. Examples: i32; Vec<(char, String)>; &T.
  • pat: a pattern. Examples: Some(t); (17, 'a'); _.
  • stmt: a single statement. Example: let x = 3.
  • block: a brace-delimited sequence of statements. Example: { log(error, "hi"); return 12; }.
  • item: an item. Examples: fn foo() { }; struct Bar;.
  • meta: a "meta item", as found in attributes. Example: cfg(target_os = "windows").
  • tt: a single token tree.

There are additional rules regarding the next token after a metavariable:

  • expr variables may only be followed by one of: => , ;
  • ty and path variables may only be followed by one of: => , : = > as
  • pat variables may only be followed by one of: => , = if in
  • Other variables may be followed by any token.

These rules provide some flexibility for Rust’s syntax to evolve without breaking existing macros.

The macro system does not deal with parse ambiguity at all. For example, the grammar $($t:ty)* $e:expr will always fail to parse, because the parser would be forced to choose between parsing $t and parsing $e. Changing the invocation syntax to put a distinctive token in front can solve the problem. In this case, you can write $(T $t:ty)* E $e:exp.

Scoping and macro import/export

Macros are expanded at an early stage in compilation, before name resolution. One downside is that scoping works differently for macros, compared to other constructs in the language.

Definition and expansion of macros both happen in a single depth-first, lexical-order traversal of a crate’s source. So a macro defined at module scope is visible to any subsequent code in the same module, which includes the body of any subsequent child mod items.

A macro defined within the body of a single fn, or anywhere else not at module scope, is visible only within that item.

If a module has the macro_use attribute, its macros are also visible in its parent module after the child’s mod item. If the parent also has macro_use then the macros will be visible in the grandparent after the parent’s mod item, and so forth.

The macro_use attribute can also appear on extern crate. In this context it controls which macros are loaded from the external crate, e.g.

#[macro_use(foo, bar)]
extern crate baz;

If the attribute is given simply as #[macro_use], all macros are loaded. If there is no #[macro_use] attribute then no macros are loaded. Only macros defined with the #[macro_export] attribute may be loaded.

To load a crate’s macros without linking it into the output, use #[no_link] as well.

An example:

macro_rules! m1 { () => (()) }

// visible here: m1

mod foo {
    // visible here: m1

    #[macro_export]
    macro_rules! m2 { () => (()) }

    // visible here: m1, m2
}

// visible here: m1

macro_rules! m3 { () => (()) }

// visible here: m1, m3

#[macro_use]
mod bar {
    // visible here: m1, m3

    macro_rules! m4 { () => (()) }

    // visible here: m1, m3, m4
}

// visible here: m1, m3, m4
# fn main() { }

When this library is loaded with #[macro_use] extern crate, only m2 will be imported.

The Rust Reference has a listing of macro-related attributes.

The variable $crate

A further difficulty occurs when a macro is used in multiple crates. Say that mylib defines

pub fn increment(x: u32) -> u32 {
    x + 1
}

#[macro_export]
macro_rules! inc_a {
    ($x:expr) => ( ::increment($x) )
}

#[macro_export]
macro_rules! inc_b {
    ($x:expr) => ( ::mylib::increment($x) )
}
# fn main() { }

inc_a only works within mylib, while inc_b only works outside the library. Furthermore, inc_b will break if the user imports mylib under another name.

Rust does not (yet) have a hygiene system for crate references, but it does provide a simple workaround for this problem. Within a macro imported from a crate named foo, the special macro variable $crate will expand to ::foo. By contrast, when a macro is defined and then used in the same crate, $crate will expand to nothing. This means we can write

#[macro_export]
macro_rules! inc {
    ($x:expr) => ( $crate::increment($x) )
}
# fn main() { }

to define a single macro that works both inside and outside our library. The function name will expand to either ::increment or ::mylib::increment.

To keep this system simple and correct, #[macro_use] extern crate ... may only appear at the root of your crate, not inside mod. This ensures that $crate is a single identifier.

The deep end

The introductory chapter mentioned recursive macros, but it did not give the full story. Recursive macros are useful for another reason: Each recursive invocation gives you another opportunity to pattern-match the macro’s arguments.

As an extreme example, it is possible, though hardly advisable, to implement the Bitwise Cyclic Tag automaton within Rust’s macro system.

macro_rules! bct {
    // cmd 0:  d ... => ...
    (0, $($ps:tt),* ; $_d:tt)
        => (bct!($($ps),*, 0 ; ));
    (0, $($ps:tt),* ; $_d:tt, $($ds:tt),*)
        => (bct!($($ps),*, 0 ; $($ds),*));

    // cmd 1p:  1 ... => 1 ... p
    (1, $p:tt, $($ps:tt),* ; 1)
        => (bct!($($ps),*, 1, $p ; 1, $p));
    (1, $p:tt, $($ps:tt),* ; 1, $($ds:tt),*)
        => (bct!($($ps),*, 1, $p ; 1, $($ds),*, $p));

    // cmd 1p:  0 ... => 0 ...
    (1, $p:tt, $($ps:tt),* ; $($ds:tt),*)
        => (bct!($($ps),*, 1, $p ; $($ds),*));

    // halt on empty data string
    ( $($ps:tt),* ; )
        => (());
}

Exercise: use macros to reduce duplication in the above definition of the bct! macro.

Common macros

Here are some common macros you’ll see in Rust code.

panic!

This macro causes the current thread to panic. You can give it a message to panic with:

panic!("oh no!");

vec!

The vec! macro is used throughout the book, so you’ve probably seen it already. It creates Vec<T>s with ease:

let v = vec![1, 2, 3, 4, 5];

It also lets you make vectors with repeating values. For example, a hundred zeroes:

let v = vec![0; 100];

assert! and assert_eq!

These two macros are used in tests. assert! takes a boolean. assert_eq! takes two values and checks them for equality. true passes, false panic!s. Like this:

// A-ok!

assert!(true);
assert_eq!(5, 3 + 2);

// nope :(

assert!(5 < 3);
assert_eq!(5, 3);

try!

try! is used for error handling. It takes something that can return a Result<T, E>, and gives T if it’s a Ok<T>, and returns with the Err(E) if it’s that. Like this:

use std::fs::File;

fn foo() -> std::io::Result<()> {
    let f = try!(File::create("foo.txt"));

    Ok(())
}

This is cleaner than doing this:

use std::fs::File;

fn foo() -> std::io::Result<()> {
    let f = File::create("foo.txt");

    let f = match f {
        Ok(t) => t,
        Err(e) => return Err(e),
    };

    Ok(())
}

unreachable!

This macro is used when you think some code should never execute:

if false {
    unreachable!();
}

Sometimes, the compiler may make you have a different branch that you know will never, ever run. In these cases, use this macro, so that if you end up wrong, you’ll get a panic! about it.

let x: Option<i32> = None;

match x {
    Some(_) => unreachable!(),
    None => println!("I know x is None!"),
}

unimplemented!

The unimplemented! macro can be used when you’re trying to get your functions to typecheck, and don’t want to worry about writing out the body of the function. One example of this situation is implementing a trait with multiple required methods, where you want to tackle one at a time. Define the others as unimplemented! until you’re ready to write them.

Procedural macros

If Rust’s macro system can’t do what you need, you may want to write a compiler plugin instead. Compared to macro_rules! macros, this is significantly more work, the interfaces are much less stable, and bugs can be much harder to track down. In exchange you get the flexibility of running arbitrary Rust code within the compiler. Syntax extension plugins are sometimes called ‘procedural macros’ for this reason.

Nightly Rust