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 start 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.
Local documentation
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:
- Put your source file in the right directory.
- Get rid of the old executable (
main.exeon Windows,maineverywhere else) and make a new one. - 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.1.0"
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.1.0 (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.1.0 (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 the 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.1.0"
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
Up and Running
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:///projects/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:///projects/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:///projects/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:///projects/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:///projects/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:///projects/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:///projects/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:///projects/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:///projects/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:///projects/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. (It also uses them for variable names, too.) We
can can call any function we’ve defined by using its name and some parentheses:
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:///projects/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:///projects/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: TYPE) {
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:///projects/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:///projects/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:///projects/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
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’. Expressions compute something, but statements bind or do
something. It’s a subtle difference. 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:///projects/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:///projects/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:///projects/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:///projects/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.
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:///projects/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.
Scalar 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. First, we’ll take a look at ‘scalar’ types, that is, types which represent a single value.
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 never negative, 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 complement’ 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 defaults 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.
Numeric operations
Rust supports the usual operations you’d expect on all of these number types:
fn main() {
// addition
let sum = 5 + 10;
// subtraction
let difference = 95.5 - 4.3;
// multiplication
let product = 4 * 30;
// division
let quotient = 56.7 / 32.2;
// modulus
let remainder = 43 % 5;
}
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
}
The main way to consume boolean values is through conditionals like if, which
we’ll see later in the chapter.
Characters
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.
Compound Types
Now that we’ve discussed scalar types, let’s talk about compound types. These types can group multiple values of scalar types into another type.
Tuples
We’ve seen tuples before, in the guise of binding or returning multiple values at once. It turns out that there’s no magic here: tuples are a general way of making a compound value that groups some number of other values with distinct types. The number of values grouped is the ‘arity’ of the tuple.
We create a tuple by writing a comma-separated list of values inside parentheses; each position in the tuple has a distinct type:
fn main() {
let tup: (i32, f64, u8) = (500, 6.4, 1);
}
Note that, unlike the examples of multiple bindings, here we bound the
single name tup to the entire tuple. We can then use pattern
matching to destructure this tuple value:
fn main() {
let tup: (i32, f64, u8) = (500, 6.4, 1);
let (x, y, z) = tup;
println!("The value of y is: {}", y);
}
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
In addition to destructuring through pattern matching, we can also access a
tuple element directly using ., 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.
}
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:///projects/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
For now, all you need to know is that a panic will crash your program. Rust’s error handling story is described in full in a later chapter.
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.
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:///projects/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
intended for direct end-user consumption. 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, Debug,
which is a bit different: intended for programmer consumption. 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:///projects/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.
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?
^~~~~~~~~~~~~~~~~~~~~~~~~~
Control flow with 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”
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:///projects/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:///projects/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:///projects/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:///projects/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:///projects/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:///projects/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.
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:///projects/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:///projects/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:///projects/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:///projects/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**
Understanding Ownership
Now that we’ve got some basic syntax under our belt, it’s time to take a look at Rust’s most unique feature: ownership. We’ll also talk about several related features: borrowing, slices, and lifetimes, as well as how Rust lays things out in memory.
Ownership
Rust’s central feature is called ‘ownership’. It is a feature that is straightforward to explain, but has deep implications for the rest of the language.
Rust is committed to both safety and speed. One of the key tools for balancing between them is “zero-cost abstractions”: the various abstractions in Rust do not pose a global performance penalty. 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 Rustaceans 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 can happen because the programmer isn’t used to thinking carefully about ownership, or is thinking about it differently from the way that Rust does. You probably will experience something similar 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. Keep at it!
This chapter will give you a foundation for understanding the rest of the language. To do so, we’re going to learn through examples, focusing on a very common data structure: strings.
Variable binding scope
Let’s take a step back and look at the very basics again. Now that we’re past
basic syntax, we won’t include all of the fn main() { stuff in examples, so
if you’re following along, you will have to put them inside of a main()
function. This lets our examples be a bit more concise, letting us focus on the
actual details, rather than boilerplate.
Anyway, here it is:
let s = "hello";
This variable binding refers to a string literal. It’s valid from the point at which it’s declared, until the end of the current scope. That is:
{ // s is not valid here, it’s not yet in scope
let s = "hello"; // s is valid from this point forward
// do stuff with s
} // this scope is now over, and s is no longer valid
In other words, there are two important points in time here:
- When
scomes ‘into scope’, it is valid. - It remains so until it ‘goes out of scope’.
At this point, things are similar to other programming languages. Let’s build
on top of this understanding by introducing a new type: String.
Strings
String literals are convenient, but they aren’t the only way that you use strings. For one thing, they’re immutable. For another, not every string is literal: what about taking user input and storing it in a string?
For this, Rust has a second string type, String. You can create a String from
a string literal using the from function:
let s = String::from("hello");
We haven’t seen the double colon (::) syntax yet. It is a kind of scope
operator, allowing us to namespace this particular from() function under the
String type itself, rather than using some sort of name like string_from().
We’ll discuss this syntax more in the “Method Syntax” and “Modules” chapters.
This kind of string can be mutated:
let mut s = String::from("hello");
s.push_str(", world!");
Memory and allocation
So, what’s the difference here? Why can String be mutated, but literals
cannot? The difference comes down to how these two types deal with memory.
In the case of a string literal, because we know the contents of the string at compile time, we can hard-code the text of the string directly into the final executable. This means that string literals are quite fast and efficient. But these properties only come from its immutability; we can’t put an arbitrary-sized blob of memory into the binary for each string!
With String, to support a mutable, growable string, we need to allocate an
unknown amount of memory to hold the contents. This means two things:
- The memory must be requested from the operating system at runtime.
- We need a way of giving this memory back to the operating system when we’re
done with our
String.
That first part is done by us: when we call String::from(), its
implementation requests the memory it needs. This is pretty much universal in
programming languages.
The second case, however, is different. In languages with a garbage collector
(‘GC’), the GC handles that second case, and we, as the programmer, don’t need
to think about it. Without GC, it’s the programmer’s responsibility to identify
when memory is no longer being used, and explicitly return it, just as it was
requested. Doing this correctly has historically been a difficult problem. If
we forget, we will waste memory. If we do it too early, we will have an invalid
variable. If we do it twice, that’s a bug too. We need to pair exactly one
allocate() with exactly one free().
Rust takes a different path. Remember our example? Here’s a version with
String:
{
let s = String::from("hello"); // s is valid from this point forward
// do stuff with s
} // this scope is now over, and s is no longer valid
We have a natural point at which we can return the memory our String needs back
to the operating system: when it goes out of scope! When a variable goes out of
scope, a special function is called. This function is called drop(), and it
is where the author of String can put the code to return the memory.
Aside: This pattern is sometimes called “Resource Aquisition Is Initialization” in C++, or “RAII” for short. While they are very similar, Rust’s take on this concept has a number of differences, and so we don’t tend to use the same term. If you’re familliar with this idea, keep in mind that it is roughly similar in Rust, but not identical.
This pattern has a profound impact on the way that Rust code is written. It may seem obvious right now, but things can get tricky in more advanced situations! Let’s go over the first one of those right now.
Move
What would you expect this code to do?
let x = 5;
let y = x;
You might say “Make a copy of 5.” That’d be correct! We now have two
bindings, x and y, and both equal 5.
Now let’s look at String. What would you expect this code to do?
let s1 = String::from("hello");
let s2 = s1;
You might say “copy the String!” This is both correct and incorrect at the
same time. It does a shallow copy of the String. What’s that mean? Well,
let’s take a look at what String looks like under the covers:

A String is made up of three parts: a pointer to the memory that holds the
contents of the string, a length, and a capacity. The length is how much memory
the String is currently using. The capacity is the total amount of memory the
String has gotten from the operating system. The difference between length
and capacity matters, but not in this context, so don’t worry about it too much
if it doesn’t make sense, and just ignore the capacity.
We’ve talked about two kinds of composite types: arrays and tuples.
Stringis a third type: astruct, which we will cover the details of in the next chapter of the book. For now, thinking aboutStringas a tuple is close enough.
When we assign s1 to s2, the String itself is copied. But not all kinds
of copying are the same. Many people draw distinctions between ‘shallow
copying’ and ‘deep copying’. We don’t use these terms in Rust. We instead say
that something is ‘moved’ or ‘cloned’. Assignment in Rust causes a ‘move’. In
other words, it looks like this:

Not this:

When moving, Rust makes a copy of the data structure itself, the contents of
s1 are copied, but if s1 contains a reference, like it does in this case,
Rust will not copy the things that those references refer to.
There’s a problem here! Both data pointers are pointing to the same place.
Why is this a problem? Well, when s2 goes out of scope, it will free the
memory that data points to. And then s1 goes out of scope, and it will
also try to free the memory that data points to! That’s bad.
So what’s the solution? Here, we stand at a crossroads. There are a few
options. One would be to declare that assignment will also copy out any data.
This works, but is inefficient: what if our String contained a novel? Also,
it only works for memory. What if, instead of a String, we had a
TcpConnection? Opening and closing a network connection is very similar to
allocating and freeing memory. The solution that we could use there is to allow
the programmer to hook into the assignment, similar to drop(), and write code
fix things up. That would work, but now, an = can run arbitrary code. That’s
also not good, and it doesn’t solve our efficiency concerns either.
Let’s take a step back: the root of the problem is that s1 and s2 both
think that they have control of the memory, and therefore needs to free it.
Instead of trying to copy the allocated memory, we could say that s1 is no
longer valid, and therefore, doesn’t need to free anything. This is in fact the
choice that Rust makes. Check it out what happens when you try to use s1
after s2 is created:
let s1 = String::from("hello");
let s2 = s1;
println!("{}", s1);
You’ll get an error like this:
5:22 error: use of moved value: `s1` [E0382]
println!("{}", s1);
^~
5:24 note: in this expansion of println! (defined in <std macros>)
3:11 note: `s1` moved here because it has type `collections::string::String`, which is moved by default
let s2 = s1;
^~
We say that s1 was moved into s2. When a value moves, its data is copied,
but the original variable binding is no longer usable. That solves our problem:

With only s2 valid, when it goes out of scope, it will free the memory, and we’re done!
Ownership Rules
This leads us to the Ownership Rules:
- Each value in Rust has a variable binding that’s called it’s ‘owner’.
- There can only be one owner at a time.
- When the owner goes out of scope, the value will be
drop()ped.
Furthermore, there’s a design choice that’s implied by this: Rust will never automatically create ‘deep’ copies of your data. Any automatic copying must be inexpensive.
Clone
But what if we do want to deeply copy the String’s data, and not just the
String itself? There’s a common method for that: clone(). Here’s an example
of clone() in action:
let s1 = String::from("hello");
let s2 = s1.clone();
println!("{}", s1);
This will work just fine. Remember our diagram from before? In this case, it is doing this:

When you see a call to clone(), you know that some arbitrary code is being
executed, which may be expensive. It’s a visual indicator that something
different is going on here.
Copy
There’s one last wrinkle that we haven’t talked about yet. This code works:
let x = 5;
let y = x;
println!("{}", x);
But why? We don’t have a call to clone(). Why didn’t x get moved into y?
For types that do not have any kind of complex storage requirements, like
integers, typing clone() is busy work. There’s no reason we would ever want
to prevent x from being valid here, as there’s no situation in which it’s
incorrect. In other words, there’s no difference between deep and shallow
copying here, so calling clone() wouldn’t do anything differently from the
usual shallow copying.
Rust has a special annotation that you can place on types, called Copy. If
a type is Copy, an older binding is still usable after assignment. Integers
are an example of such a type; most of the primitive types are Copy.
While we haven’t talked about how to mark a type as Copy yet, you might ask
yourself “what happens if we made String Copy?” The answer is, you cannot.
Remember drop()? Rust will not let you make something Copy if it has
implemented drop(). If you need to do something special when the value goes
out of scope, being Copy will be an error.
So what types are Copy? You can check the documentation for the given type to
be sure, but as a rule of thumb, any group of simple scalar values can be
Copy, but nothing that requires allocation or is some form of resource is Copy.
And you can’t get it wrong: the compiler will throw an error if you try to use
a type that moves incorrectly, as we saw above.
Here’s some types that you’ve seen so far that are Copy:
- All of the integer types, like
u32. - The booleans,
trueandfalse. - All of the floating point types, like
f64. - Tuples, but only if they contain types which are also
Copy.(i32, i32)isCopy, but(i32, String)is not!
Ownership and functions
Passing a value to a function has similar semantics as assigning it:
fn main() {
let s = String::from("hello");
takes_ownership(s);
let x = 5;
makes_copy(x);
}
fn takes_ownership(some_string: String) {
println!("{}", some_string);
}
fn makes_copy(some_integer: i32) {
println!("{}", some_integer);
}
Passing a binding to a function will move or copy, just like assignment. Here’s the same example, but with some annotations showing where things go into and out of scope:
fn main() {
let s = String::from("hello"); // s goes into scope.
takes_ownership(s); // s moves into the function...
// ... and so is no longer valid here.
let x = 5; // x goes into scope.
makes_copy(x); // x would move into the function,
// but i32 is Copy, so it’s okay to still
// use x afterward.
} // Here, x goes out of scope, then s. But since s was moved, nothing special
// happens.
fn takes_ownership(some_string: String) { // some_string comes into scope.
println!("{}", some_string);
} // Here, some_string goes out of scope and `drop()` is called. The backing
// memory is freed.
fn makes_copy(some_integer: i32) { // some_integer comes into scope.
println!("{}", some_integer);
} // Here, some_integer goes out of scope. Nothing special happens.
Remember: If we tried to use s after the call to takes_ownership(), Rust
would throw a compile-time error! These static checks protect us from mistakes.
Returning values can also transfer ownership:
fn main() {
let s1 = gives_ownership();
let s2 = String::from("hello");
let s3 = takes_and_gives_back(s2);
}
fn gives_ownership() -> String {
let some_string = String::from("hello");
some_string
}
fn takes_and_gives_back(a_string: String) -> String {
a_string
}
With simililar annotations:
fn main() {
let s1 = gives_ownership(); // gives_ownership moves its return
// value into s1.
let s2 = String::from("hello"); // s2 comes into scope
let s3 = takes_and_gives_back(s2); // s2 is moved into
// takes_and_gives_back, which also
// moves its return value into s3.
} // Here, s3 goes out of scope, and is dropped. s2 goes out of scope, but was
// moved, so nothing happens. s1 goes out of scope, and is dropped.
fn gives_ownership() -> String { // gives_ownership will move its
// return value into the function
// that calls it.
let some_string = String::from("hello"); // some_string comes into scope.
some_string // some_string is returned, and
// moves out to the calling
// function.
}
// takes_and_gives_back will both take a String and return one
fn takes_and_gives_back(a_string: String) -> String { // a_string comes into scope
a_string // a_string is returned, and moves out to the calling function
}
It’s the same pattern, every time: assigning something moves it, and when an
owner goes out of scope, if it hasn’t been moved, it will drop().
This might seem a bit tedious, and it is. What if I want to let a function use a value, but not take ownership? It’s quite annoying that anything I pass in also needs passed back. Look at this function:
fn main() {
let s1 = String::from("hello");
let (s2, len) = calculate_length(s1);
println!("The length of '{}' is {}.", s2, len);
}
fn calculate_length(s: String) -> (String, usize) {
let length = s.len(); // len() returns the length of a String.
(s, length)
}
This is too much ceremony: we have to use a tuple to give back the String as
well as the length. It’s a lot of work for a pattern that should be common.
Luckily for us, Rust has such a feature, and it’s what the next section is about.
References and Borrowing
At the end of the last section, we had some example Rust that wasn’t very good. Here it is again:
fn main() {
let s1 = String::from("hello");
let (s2, len) = calculate_length(s1);
println!("The length of '{}' is {}.", s2, len);
}
fn calculate_length(s: String) -> (String, usize) {
let length = s.len(); // len() returns the length of a String.
(s, length)
}
The issue here is that we have to return the String back to the calling
function so that it could still use it.
There is a better way. It looks like this:
fn main() {
let s1 = String::from("hello");
let len = calculate_length(&s1);
println!("The length of '{}' is {}.", s1, len);
}
fn calculate_length(s: &String) -> usize {
let length = s.len();
length
}
First, you’ll notice all of the tuple stuff is gone. Next, that we pass &s1
into calculate_lengths(). And in its definition, we take &String rather
than String.
These &s are called ‘references’, and they allow you to refer to some value
without taking ownership of it. Here’s a diagram:
DIAGRAM GOES HERE of a &String pointing at a String, with (ptr, len, capacity)
Let’s take a closer look at the function call here:
# fn calculate_length(s: &String) -> usize {
# let length = s.len();
#
# length
# }
let s1 = String::from("hello");
let len = calculate_length(&s1);
The &s1 syntax lets us create a reference from s1. This reference refers
to the value of s1, but does not own it. Because it does not own it, the
value it points to will not be dropped when the reference goes out of scope.
Likewise, the signature of the function uses & to indicate that it takes
a reference as an argument:
Let’s add some explanatory annotations:
fn calculate_length(s: &String) -> usize { // s is a reference to a String
let length = s.len();
length
} // Here, s goes out of scope. But since it does not have ownership of what
// it refers to, nothing happens.
It’s the same process as before, except that because we don’t have ownership, we don’t drop what a reference points to when the reference goes out of scope. This lets us write functions which take references as arguments instead of the values themselves, so that we won’t need to return them to give back ownership.
There’s another word for what references do, and that’s ‘borrowing’. Just like with real life, if I own something, you can borrow it from me. When you’re done, you have to give it back.
Speaking of which, what if you try to modify something you borrow from me? Try this code out. Spoiler alert: it doesn’t work:
fn main() {
let s = String::from("hello");
change(&s);
}
fn change(some_string: &String) {
some_string.push_str(", world"); // push_str() appends a literal to a String
}
Here’s the error:
8:16 error: cannot borrow immutable borrowed content `*some_string` as mutable
some_string.push_str(", world"); // push_str() appends a literal to a String
^~~~~~~~~~~
Just like bindings are immutable by default, so are references. We’re not allowed to modify something we have a reference to.
Mutable references
We can fix this bug! Just a small tweak:
fn main() {
let mut s = String::from("hello");
change(&mut s);
}
fn change(some_string: &mut String) {
some_string.push_str(", world"); // push_str() appends a literal to a String
}
First, we had to change s to be mut. Then, we had to create a mutable reference
with &mut s and accept a mutable reference with some_string: &mut String.
Mutable references have one big restriction, though. This code fails:
let mut s = String::from("hello");
let r1 = &mut s;
let r2 = &mut s;
Here’s the error:
5:20 error: cannot borrow `s` as mutable more than once at a time [E0499]
let r2 = &mut s;
^
4:20 note: previous borrow of `s` occurs here; the mutable borrow prevents
subsequent moves, borrows, or modification of `s` until the borrow
ends
let r1 = &mut s;
^
7:2 note: previous borrow ends here
fn main() {
}
^
The error is what it says on the tin: you cannot borrow something more than once at a time in a mutable fashion. This restriction allows for mutation, but in a very controlled fashion. It is something that new Rustaceans struggle with, because most languages let you mutate whenever you’d like.
As always, we can use {}s to create a new scope, allowing for multiple mutable
references. Just not simultaneous ones:
let mut s = String::from("hello");
{
let r1 = &mut s;
} // r1 goes out of scope here, so we can make a new reference with no problems.
let r2 = &mut s;
There is a simlar rule for combining the two kinds of references. This code errors:
let mut s = String::from("hello");
let r1 = &s; // no problem
let r2 = &s; // no problem
let r3 = &mut s; // BIG PROBLEM
Here’s the error:
19: 6:20 error: cannot borrow `s` as mutable because it is also borrowed as
immutable [E0502]
let r3 = &mut s; // BIG PROBLEM
^
15: 4:16 note: previous borrow of `s` occurs here; the immutable borrow
prevents subsequent moves or mutable borrows of `s` until the
borrow ends
let r1 = &s; // no problem
^
8:2 note: previous borrow ends here
fn main() {
}
^
Whew! We also cannot have a mutable reference while we have an immutable one. Users of an immutable reference don’t expect the values to suddenly change out from under them! Multiple immutable references are okay, however.
Dangling references
In languages with pointers, it’s easy to create a “dangling pointer” by freeing some memory while keeping around a pointer to that memory. In Rust, by contrast, the compiler guarantees that references will never be dangling: if we have a reference to something, the compiler will ensure that it will not go out of scope before the reference does.
Let’s try to create a dangling reference:
fn main() {
let reference_to_nothing = dangle();
}
fn dangle() -> &String {
let s = String::from("hello");
&s
}
Here’s the error:
error: missing lifetime specifier [E0106]
fn dangle() -> &String {
^~~~~~~
help: this function’s return type contains a borrowed value, but there is no
value for it to be borrowed from
help: consider giving it a ‘static lifetime
This error message refers to a feature we haven’t learned about yet, ‘lifetimes’. The message does contain the key to why this code is a problem, though:
this function’s return type contains a borrowed value, but there is no value
for it to be borrowed from
Let’s examine exactly what happens with dangle():
fn dangle() -> &String { // dangle returns a reference to a String
let s = String::from("hello"); // s is a new String
&s // we return a reference to the String, s
} // Here, s goes out of scope, and is dropped. Its memory goes away.
// Danger!
Because s is created inside of dangle(), when the code of dangle() is
finished, it will be deallocated. But we tried to return a reference to it.
That means this reference would be pointing to an invalid String! That’s
no good. Rust won’t let us do this.
The correct code here is to return the String directly:
fn no_dangle() -> String {
let s = String::from("hello");
s
}
This works, no problem. Ownership is moved out, nothing is deallocated.
The Rules of References
Here’s a recap of what we’ve talked about:
- At any given time, you may have either, but not both of:
- One mutable reference.
- Any number of immutable references .
- References must always be valid.
While these rules are not complicated on their own, they can be tricky when applied to real code. Let’s work through a number of examples to help build our understanding.
More Examples
COMING SOON
Slices
So far, we’ve talked about types that have ownership, like String, and ones
that don’t, like &String. There is a second kind of type which does not have
ownership: slices. Slices let you reference a contiguous sequence of elements
in a collection, rather than the whole collection itself.
Here’s a small programming problem: write a function which takes a string, and returns the first word you find. If we don’t find a space in the string, then the whole string is a word, so the whole thing should be returned.
Let’s think about the signature of this function:
fn first_word(s: &String) -> ?
This function, first_word, takes a &String as an argument. We don’t want
ownership, so this is fine. But what should we return? We don’t really have a
way to talk about part of a string. We could return the index of the end of
the word, though. Let’s try that:
fn first_word(s: &String) -> usize {
let bytes = s.as_bytes();
for (i, &byte) in bytes.iter().enumerate() {
if byte == 32 {
return i;
}
}
s.len()
}
Let’s break that down a bit:
fn first_word(s: &String) -> usize {
// Since we need to go through the String element by element, and
// check if a value is a space, we will convert our String to an
// array of bytes, using the `.as_bytes()` method.
let bytes = s.as_bytes();
// We discussed using the iter() method with for in Chapter 3.7. Here,
// we’re adding another method: enumerate(). While iter() returns each
// element, enumerate() modifies the result of iter(), and returns a
// tuple instead. The first element of the tuple is the index, and the
// second element is a reference to the element itself. This is a bit
// nicer than calculating the index ourselves.
//
// Since it’s a tuple, we can use patterns, just like elsewhere in Rust.
// So we match against the tuple with i for the index, and &byte for
// the byte itself.
for (i, &byte) in bytes.iter().enumerate() {
// 32 is the value of a space in UTF-8
if byte == 32 {
// We found a space! Return this position.
return i;
}
}
// If we got here, we didn’t find a space, so this whole thing must be a
// word. So return the length.
s.len()
}
This works, but there’s a problem. We’re returning a usize on its own, but
it’s only a meaningful number in the context of the &String itself. In other
words, because it’s a separate value from the String, there’s no guarantee
that it will still be valid in the future. Consider this:
# fn first_word(s: &String) -> usize {
# let bytes = s.as_bytes();
#
# for (i, &byte) in bytes.iter().enumerate() {
# if byte == 32 {
# return i;
# }
# }
#
# s.len()
# }
fn main() {
let mut s = String::from("hello world");
let word = first_word(&s);
s.clear(); // This empties the String, making it equal to "".
// word is now totally invalid! There’s no more word here.
}
This is bad! It’s even worse if we wanted to write a second_word()
function. Its signature would have to look like this:
fn second_word(s: &String) -> (usize, usize) {
Now we’re tracking both a start and and ending index. Even more chances for things to go wrong. We now have three unrelated variable bindings floating around which need to be kept in sync.
Luckily, Rust has a solution to this probem: string slices.
String slices
A string slice looks like this:
let s = String::from("hello world");
let hello = &s[0..5];
let world = &s[6..11];
This looks just like taking a reference to the whole String, but with the
extra [0..5] bit. Instead of being a reference to the entire String,
it’s a reference to an internal position in the String, but it also keeps
track of the number of elements that it refers to as well. In other words,
it looks like this:
DIAGRAM GOES HERE of s, hello, and world
Note that the internal position is specified through byte-offsets, not
characters. The offset to the first byte of a String is 0 and the
trailing number should point to the first byte that is not included
in the slice.
With Rust’s .. syntax, if you want to start at zero, you can drop the zero.
In other words, these are equal:
let s = String::from("hello");
let slice = &s[0..2];
let slice = &s[..2];
By the same token, if your slice should include the last byte of the
String, you can drop the trailing number. In other words, these are
equal:
let s = String::from("hello");
let len = s.len();
let slice = &s[0..len];
let slice = &s[0..];
With this in mind, let’s re-write first_word() to return a slice:
fn first_word(s: &String) -> &str {
let bytes = s.as_bytes();
for (i, &byte) in bytes.iter().enumerate() {
if byte == 32 {
return &s[0..i];
}
}
&s[..]
}
Now, we have a single value, the &str. It contains both elements that we care
about: a reference to the starting point, and the number of elements.
This would also work for a second_word():
fn second_word(s: &String) -> &str {
Same deal. We now have a straightforward API, that’s much harder to mess up.
But what about our error condition from before? Slices also fix that. Using
the slice version of first_word() will throw an error:
# fn first_word(s: &String) -> &str {
# let bytes = s.as_bytes();
#
# for (i, &byte) in bytes.iter().enumerate() {
# if byte == 32 {
# return &s[0..i];
# }
# }
#
# &s[..]
# }
fn main() {
let mut s = String::from("hello world");
let word = first_word(&s);
s.clear(); // Error!
}
Here’s the error:
17:6 error: cannot borrow `s` as mutable because it is also borrowed as
immutable [E0502]
s.clear(); // Error!
^
15:29 note: previous borrow of `s` occurs here; the immutable borrow prevents
subsequent moves or mutable borrows of `s` until the borrow ends
let word = first_word(&s);
^
18:2 note: previous borrow ends here
fn main() {
}
^
Remember the borrowing rules? If we have an immutable reference to something,
we cannot also take a mutable reference. Since clear() needs to truncate the
String, it tries to take a mutable reference, which fails. Not only has Rust
made our API easier to use, but it’s also eliminated an entire class of errors
at compile time!
String literals are slices
Remember how we talked about string literals being stored inside of the binary itself? Now that we know about slices, we can now properly understand string literals.
let s = "Hello, world!";
The type of s here is &str: It’s a slice, pointing to that specific point
of the binary. This is also why string literals are immutable; &str is an
immutable reference.
String slices as arguments
Knowing that you can take slices of both literals and Strings leads us to
one more improvement on first_word(), and that’s its signature:
fn first_word(s: &String) -> &str {
A more experienced Rustacean would write this one instead:
fn first_word(s: &str) -> &str {
Why is this? Well, we aren’t trying to modify s at all. And we can take
a string slice that’s the full length of a String, so we haven’t lost
the ability to talk about full Strings. And additionally, we can take
string slices of string literals too, so this function is more useful, but
with no loss of functionality:
# fn first_word(s: &str) -> &str {
# let bytes = s.as_bytes();
#
# for (i, &byte) in bytes.iter().enumerate() {
# if byte == 32 {
# return &s[0..i];
# }
# }
#
# &s[..]
# }
fn main() {
let s = String::from("hello world");
let word = first_word(&s[..]);
let s = "hello world";
let word = first_word(&s[..]);
let word = first_word(s); // since literals are &strs, this works too!
}
Other slices
String slices, as you might imagine, are specific to strings. But there’s a more general slice type, too. Consider arrays:
let a = [1, 2, 3, 4, 5];
Just like we may want to refer to a part of a string, we may want to refer to part of an array:
let a = [1, 2, 3, 4, 5];
let slice = &a[1..3];
This slice has the type &[i32]. It works the exact same way as string slices
do, with a reference to the first element, and a length. You’ll use this kind
of slice for all sorts of other collections. We’ll discuss these other slices
in detail when we talk about vectors, in Chapter 9.1.
Structs
So far, all of the data types we’ve seen allow us to have a single value
at a time. structs give us the ability to package up multiple values and
keep them in one related structure.
Let’s write a program which calculates the distance between two points.
We’ll start off with single variable bindings, and then refactor it to
use structs instead.
Let’s make a new project with Cargo:
$ cargo new --bin points
$ cd points
Here’s a short program which calculates the distance between two points. Put
it into your src/main.rs:
fn main() {
let x1 = 0.0;
let y1 = 5.0;
let x2 = 12.0;
let y2 = 0.0;
let answer = distance(x1, y1, x2, y2);
println!("Point 1: ({}, {})", x1, y1);
println!("Point 2: ({}, {})", x2, y2);
println!("Distance: {}", answer);
}
fn distance(x1: f64, y1: f64, x2: f64, y2: f64) -> f64 {
let x_squared = f64::powi(x2 - x1, 2);
let y_squared = f64::powi(y2 - y1, 2);
f64::sqrt(x_squared + y_squared)
}
Let's try running this program with cargo run:
$ cargo run
Compiling points v0.1.0 (file:///projects/points)
Running `target/debug/points`
Point 1: (0, 5)
Point 2: (12, 0)
Distance: 13
Let's take a quick look at distance() before we move forward:
fn distance(x1: f64, y1: f64, x2: f64, y2: f64) -> f64 {
let x_squared = f64::powi(x2 - x1, 2);
let y_squared = f64::powi(y2 - y1, 2);
f64::sqrt(x_squared + y_squared)
}
To find the distance between two points, we can use the Pythagorean Theorem. The theorem is named after Pythagoras, who was the first person to mathematically prove this formula. The details aren't that important, to be honest. There's a few things that we haven't discussed yet, though.
f64::powi(2.0, 3)
The double colon (::) here is a namespace operator. We haven’t talked about
modules yet, but you can think of the powi() function as being scoped inside
of another name. In this case, the name is f64, the same as the type. The
powi() function takes two arguments: the first is a number, and the second is
the power that it raises that number to. In this case, the second number is an
integer, hence the ‘i’ in its name. Similarly, sqrt() is a function under the
f64 module, which takes the square root of its argument.
Why structs?
Our little program is okay, but we can do better. The key is in the signature
of distance():
fn distance(x1: f64, y1: f64, x2: f64, y2: f64) -> f64 {
The distance function is supposed to calculate the distance between two points.
But our distance function calculates some distance between four numbers. The
first two and last two arguments are related, but that’s not expressed anywhere
in our program itself. We need a way to group (x1, y1) and (x2, y2)
together.
We’ve already discussed one way to do that: tuples. Here’s a version of our program which uses tuples:
fn main() {
let p1 = (0.0, 5.0);
let p2 = (12.0, 0.0);
let answer = distance(p1, p2);
println!("Point 1: {:?}", p1);
println!("Point 2: {:?}", p2);
println!("Distance: {}", answer);
}
fn distance(p1: (f64, f64), p2: (f64, f64)) -> f64 {
let x_squared = f64::powi(p2.0 - p1.0, 2);
let y_squared = f64::powi(p2.1 - p1.1, 2);
f64::sqrt(x_squared + y_squared)
}
This is a little better, for sure. Tuples let us add a little bit of structure. We’re now passing two arguments, so that’s more clear. But it’s also worse. Tuples don’t give names to their elements, and so our calculation has gotten much more confusing:
p2.0 - p1.0
p2.1 - p1.1
When writing this example, your authors almost got it wrong themselves! Distance
is all about x and y points, but now it’s all about 0 and 1. This isn’t
great.
Enter structs. We can transform our tuples into something with a name:
let p1 = (0.0, 5.0);
struct Point {
x: f64,
y: f64,
}
let p1 = Point { x: 0.0, y: 5.0 };
Here’s what declaring a struct looks like:
struct NAME {
NAME: TYPE,
}
The NAME: TYPE bit is called a ‘field’, and we can have as many or as few of
them as you’d like. If you have none of them, drop the {}s:
struct Foo;
structs with no fields are called ‘unit structs’, and are used in certain
advanced situations. We will just ignore them for now.
You can access the field of a struct in the same way you access an element of a tuple, except you use its name:
let p1 = (0.0, 5.0);
let x = p1.0;
struct Point {
x: f64,
y: f64,
}
let p1 = Point { x: 0.0, y: 5.0 };
let x = p1.x;
Let’s convert our program to use our Point struct. Here’s what it looks
like now:
#[derive(Debug,Copy,Clone)]
struct Point {
x: f64,
y: f64,
}
fn main() {
let p1 = Point { x: 0.0, y: 5.0};
let p2 = Point { x: 12.0, y: 0.0};
let answer = distance(p1, p2);
println!("Point 1: {:?}", p1);
println!("Point 2: {:?}", p2);
println!("Distance: {}", answer);
}
fn distance(p1: Point, p2: Point) -> f64 {
let x_squared = f64::powi(p2.x - p1.x, 2);
let y_squared = f64::powi(p2.y - p1.y, 2);
f64::sqrt(x_squared + y_squared)
}
Our function signature for distance() now says exactly what we mean: it
calculates the distance between two Points. And rather than 0 and 1,
we’ve got back our x and y. This is a win for clarity.
There’s one other thing that’s a bit strange here, this annotation on our
struct declaration:
#[derive(Debug,Copy,Clone)]
struct Point {
We haven’t yet talked about traits, but we did talk about Debug when we
discussed arrays. This derive attribute allows us to tweak the behavior of
our Point. In this case, we are opting into copy semantics, and everything
that implements Copy must implement Clone.