Files
book/print.html
T

2943 lines
136 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>The Rust Programming Language</title>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<base href="">
<link rel="stylesheet" href="book.css">
<link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
<link rel="shortcut icon" href="favicon.png">
<!-- Font Awesome -->
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
<link rel="stylesheet" href="highlight.css">
<link rel="stylesheet" href="tomorrow-night.css">
<!-- MathJax -->
<script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<!-- Fetch JQuery from CDN but have a local fallback -->
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
if (typeof jQuery == 'undefined') {
document.write(unescape("%3Cscript src='jquery.js'%3E%3C/script%3E"));
}
</script>
</head>
<body>
<!-- Set the theme before any content is loaded, prevents flash -->
<script type="text/javascript">
var theme = localStorage.getItem('theme');
if (theme == null) { theme = 'light'; }
$('body').removeClass().addClass(theme);
</script>
<!-- Hide / unhide sidebar before it is displayed -->
<script type="text/javascript">
var sidebar = localStorage.getItem('sidebar');
if (sidebar === "hidden") { $("html").addClass("sidebar-hidden") }
else if (sidebar === "visible") { $("html").addClass("sidebar-visible") }
</script>
<div id="sidebar" class="sidebar">
<ul class="chapter"><li><a href="introduction.html"><strong>1.</strong> Introduction</a></li><li><ul class="section"><li><a href="installation.html"><strong>1.1.</strong> Installation</a></li><li><a href="hello-world.html"><strong>1.2.</strong> Hello, World!</a></li><li><a href="design.html"><strong>1.3.</strong> The Design of Rust</a></li></ul></li><li><strong>2.</strong> Tutorial</li><li><a href="up-and-running.html"><strong>3.</strong> Up and Running</a></li><li><ul class="section"><li><a href="variable-bindings.html"><strong>3.1.</strong> Variable Bindings</a></li><li><a href="functions.html"><strong>3.2.</strong> Functions</a></li><li><a href="scalar-types.html"><strong>3.3.</strong> Scalar Types</a></li><li><a href="compound-types.html"><strong>3.4.</strong> Compound Types</a></li><li><a href="comments.html"><strong>3.5.</strong> Comments</a></li><li><a href="if.html"><strong>3.6.</strong> Control flow with <code>if</code></a></li><li><a href="loops.html"><strong>3.7.</strong> Loops</a></li></ul></li><li><a href="understanding-ownership.html"><strong>4.</strong> Understanding Ownership</a></li><li><ul class="section"><li><a href="ownership.html"><strong>4.1.</strong> Ownership</a></li><li><a href="references-and-borrowing.html"><strong>4.2.</strong> References &amp; Borrowing</a></li><li><a href="slices.html"><strong>4.3.</strong> Slices</a></li></ul></li><li><a href="structs.html"><strong>5.</strong> Structs</a></li><li><ul class="section"><li><strong>5.1.</strong> Method Syntax</li><li><strong>5.2.</strong> Generics</li><li><strong>5.3.</strong> Advanced</li></ul></li><li><strong>6.</strong> Enums</li><li><ul class="section"><li><strong>6.1.</strong> Match</li><li><strong>6.2.</strong> Patterns</li><li><strong>6.3.</strong> Option</li><li><strong>6.4.</strong> if let</li></ul></li><li><strong>7.</strong> Crates &amp; Modules</li><li><strong>8.</strong> Error Handling</li><li><strong>9.</strong> Basic Collections</li><li><ul class="section"><li><strong>9.1.</strong> Vectors</li><li><strong>9.2.</strong> Strings</li><li><strong>9.3.</strong> <code>HashMap&lt;K, V&gt;</code></li></ul></li><li><strong>10.</strong> Lifetimes</li><li><strong>11.</strong> Traits</li><li><strong>12.</strong> Closures</li><li><strong>13.</strong> Iterators</li><li><strong>14.</strong> I/O</li><li><ul class="section"><li><strong>14.1.</strong> <code>Read</code> &amp; <code>Write</code></li><li><strong>14.2.</strong> <code>std::fs</code></li><li><strong>14.3.</strong> <code>std::path</code></li><li><strong>14.4.</strong> <code>std::env</code></li></ul></li><li><strong>15.</strong> Testing</li><li><strong>16.</strong> Smart Pointers</li><li><ul class="section"><li><strong>16.1.</strong> <code>Deref</code></li><li><strong>16.2.</strong> <code>Deref</code> coercions</li><li><strong>16.3.</strong> <code>Box&lt;T&gt;</code></li><li><strong>16.4.</strong> <code>Rc&lt;T&gt;</code></li></ul></li><li><strong>17.</strong> Concurrency</li><li><ul class="section"><li><strong>17.1.</strong> Threads</li><li><strong>17.2.</strong> <code>Send</code> &amp; <code>Sync</code></li><li><strong>17.3.</strong> <code>Arc&lt;T&gt;</code></li><li><strong>17.4.</strong> <code>Mutex&lt;T&gt;</code></li><li><strong>17.5.</strong> <code>Channels</code></li></ul></li><li><strong>18.</strong> Unsafe Rust</li><li><ul class="section"><li><strong>18.1.</strong> Raw Pointers</li><li><strong>18.2.</strong> transmute</li></ul></li><li><strong>19.</strong> FFI</li><li><ul class="section"><li><strong>19.1.</strong> Conditional Compilation</li><li><strong>19.2.</strong> Bindings to C</li><li><strong>19.3.</strong> Using Rust from Other Languages</li><li><strong>19.4.</strong> <code>static</code></li></ul></li><li><strong>20.</strong> Cargo</li><li><ul class="section"><li><strong>20.1.</strong> Crates.io</li></ul></li><li><strong>21.</strong> Advanced Type System Features</li><li><ul class="section"><li><strong>21.1.</strong> Associated Types</li><li><strong>21.2.</strong> Trait Objects</li><li><strong>21.3.</strong> UFCS</li><li><strong>21.4.</strong> Coherence</li></ul></li><li><strong>22.</strong> Interior mutability</li><li><ul class="section"><li><strong>22.1.</strong> <code>Cell&lt;T&gt;</code></li><li><strong>22.2.</strong> <code>RefCell&lt;T&gt;</code></li></ul></li><li><strong>23.</strong> Macros</li><li><strong>24.</strong> Nightly Rust</li></ul>
</div>
<div id="page-wrapper" class="page-wrapper">
<div class="page">
<div id="menu-bar" class="menu-bar">
<div class="left-buttons">
<i id="sidebar-toggle" class="fa fa-bars"></i>
<i id="theme-toggle" class="fa fa-paint-brush"></i>
</div>
<h1 class="menu-title">The Rust Programming Language</h1>
<div class="right-buttons">
<i id="print-button" class="fa fa-print" title="Print this book"></i>
</div>
</div>
<div id="content" class="content">
<h1>Introduction</h1>
<p>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.</p>
<p>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.</p>
<p>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.</p>
<h2>Contributing to the book</h2>
<p>This book is open source. If you find an error, please don’t hesitate to file an
issue or send a pull request <a href="https://github.com/rust-lang/book">on GitHub</a>.</p>
<h1>Installation</h1>
<p>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.</p>
<p>We’ll be showing off a number of commands using a terminal, and those lines all
start with <code>$</code>. We don't need to type in the <code>$</code>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: <code>$</code> for commands run as our regular user, and <code>#</code>
for commands we should be running as an administrator.</p>
<h2>Installing on Linux or Mac</h2>
<p>If we're on Linux or a Mac, all we need to do is open a terminal and type this:</p>
<pre><code class="language-bash">$ curl -sSf https://static.rust-lang.org/rustup.sh | sh
</code></pre>
<p>This will download a script, and start the installation. If it all goes well,
you’ll see this appear:</p>
<pre><code class="language-text">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=&lt;path&gt; 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)
</code></pre>
<p>From here, press <code>y</code> for ‘yes’, and then follow the rest of the prompts.</p>
<h2>Installing on Windows</h2>
<p>If you're on Windows, please download the appropriate <a href="https://www.rust-lang.org/install.html">installer</a>.</p>
<h2>Uninstalling</h2>
<p>Uninstalling Rust is as easy as installing it. On Linux or Mac, just run
the uninstall script:</p>
<pre><code class="language-bash">$ sudo /usr/local/lib/rustlib/uninstall.sh
</code></pre>
<p>If we used the Windows installer, we can re-run the <code>.msi</code> and it will give us
an uninstall option.</p>
<h2>Troubleshooting</h2>
<p>If we've got Rust installed, we can open up a shell, and type this:</p>
<pre><code class="language-bash">$ rustc --version
</code></pre>
<p>You should see the version number, commit hash, and commit date.</p>
<p>If you do, Rust has been installed successfully! Congrats!</p>
<p>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 &quot;Change&quot; on the &quot;Change,
repair, or remove installation&quot; page and ensure &quot;Add to PATH&quot; is checked.</p>
<p>If not, there are a number of places where we can get help. The easiest is
<a href="irc://irc.mozilla.org/#rust">the #rust IRC channel on irc.mozilla.org</a>, which we can access through
<a href="http://chat.mibbit.com/?server=irc.mozilla.org&amp;channel=%23rust">Mibbit</a>. 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 <a href="https://users.rust-lang.org/">the user’s forum</a>, and <a href="http://stackoverflow.com/questions/tagged/rust">Stack Overflow</a>.</p>
<h2>Local documentation</h2>
<p>This installer also installs a copy of the documentation locally, so we can
read it offline. On UNIX systems, <code>/usr/local/share/doc/rust</code> is the location.
On Windows, it's in a <code>share/doc</code> directory, inside the directory to which Rust
was installed.</p>
<h1>Hello, world!</h1>
<p>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.</p>
<p>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.</p>
<blockquote>
<p>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.</p>
</blockquote>
<h2>Creating a Project File</h2>
<p>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 <em>projects</em> 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:</p>
<pre><code class="language-bash">$ mkdir ~/projects
$ cd ~/projects
$ mkdir hello_world
$ cd hello_world
</code></pre>
<blockquote>
<p>Note: If you’re on Windows and not using PowerShell, the <code>~</code> may not work.
Consult the documentation for your shell for more details.</p>
</blockquote>
<h2>Writing and Running a Rust Program</h2>
<p>Next, make a new source file and call it <em>main.rs</em>. Rust files always end
in a <em>.rs</em> extension. If you’re using more than one word in your filename, use
an underscore to separate them; for example, you'd use <em>hello_world.rs</em> rather
than <em>helloworld.rs</em>.</p>
<p>Now open the <em>main.rs</em> file you just created, and type the following code:</p>
<pre><code class="language-rust">fn main() {
println!(&quot;Hello, world!&quot;);
}
</code></pre>
<p>Save the file, and go back to your terminal window. On Linux or OSX, enter the
following commands:</p>
<pre><code class="language-bash">$ rustc main.rs
$ ./main
Hello, world!
</code></pre>
<p>In Windows, just replace <code>main</code> with <code>main.exe</code>. Regardless of your operating
system, you should see the string <code>Hello, world!</code> print to the terminal. If you
did, then congratulations! You've officially written a Rust program. That makes
you a Rust programmer! Welcome.</p>
<h2>Anatomy of a Rust Program</h2>
<p>Now, let’s go over what just happened in your &quot;Hello, world!&quot; program in
detail. Here's the first piece of the puzzle:</p>
<pre><code class="language-rust">fn main() {
}
</code></pre>
<p>These lines define a <em>function</em> in Rust. The <code>main</code> function is special: it's
the beginning of every Rust program. The first line says, “I’m declaring a
function named <code>main</code> that takes no arguments and returns nothing.” If there
were arguments, they would go inside the parentheses (<code>(</code> and <code>)</code>), and because
we aren’t returning anything from this function, we can omit the return type
entirely.</p>
<p>Also note that the function body is wrapped in curly braces (<code>{</code> and <code>}</code>). 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.</p>
<p>Inside the <code>main()</code> function:</p>
<pre><code class="language-rust"> println!(&quot;Hello, world!&quot;);
</code></pre>
<p>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.</p>
<p>The second important part is the <code>println!()</code> line. This is calling a Rust
<em><a href="macros.html">macro</a></em>, which is how metaprogramming is done in Rust. If it were calling a
function instead, it would look like this: <code>println()</code> (without the !). We'll
discuss Rust macros in more detail later, but for now you just need to
know that when you see a <code>!</code> that means that you’re calling a macro instead of
a normal function.</p>
<p>Next is <code>&quot;Hello, world!&quot;</code> which is a <em>string</em>. We pass this string as an
argument to <code>println!</code>, which prints the string to the screen. Easy enough!</p>
<p>The line ends with a semicolon (<code>;</code>). Rust is an <em>expression oriented</em>
language, which means that most things are expressions, rather than statements.
The <code>;</code> indicates that this expression is over, and the next one is ready to
begin. Most lines of Rust code end with a <code>;</code>.</p>
<h2>Compiling and Running Are Separate Steps</h2>
<p>In &quot;Writing and Running a Rust Program&quot;, we showed you how to run a newly
created program. We'll break that process down and examine each step now.</p>
<p>Before running a Rust program, you have to compile it. You can use the Rust
compiler by entering the <code>rustc</code> command and passing it the name of your source
file, like this:</p>
<pre><code class="language-bash">$ rustc main.rs
</code></pre>
<p>If you come from a C or C++ background, you'll notice that this is similar to
<code>gcc</code> or <code>clang</code>. After compiling successfully, Rust should output a binary
executable, which you can see on Linux or OSX by entering the <code>ls</code> command in
your shell as follows:</p>
<pre><code class="language-bash">$ ls
main main.rs
</code></pre>
<p>On Windows, you'd enter:</p>
<pre><code class="language-bash">$ dir
main.exe main.rs
</code></pre>
<p>This shows we have two files: the source code, with an <code>.rs</code> extension, and the
executable (<code>main.exe</code> on Windows, <code>main</code> everywhere else). All that's left to
do from here is run the <code>main</code> or <code>main.exe</code> file, like this:</p>
<pre><code class="language-bash">$ ./main # or main.exe on Windows
</code></pre>
<p>If <em>main.rs</em> were your &quot;Hello, world!&quot; program, this would print <code>Hello, world!</code> to your terminal.</p>
<p>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
<em>ahead-of-time compiled</em> 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 <code>.rb</code> or <code>.py</code> or <code>.js</code> 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.</p>
<p>Just compiling with <code>rustc</code> 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.</p>
<h1>Hello, Cargo!</h1>
<p>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.</p>
<p>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.</p>
<p>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:</p>
<pre><code class="language-bash">$ cargo --version
</code></pre>
<p>Into a terminal. If you see a version number, great! If you see an error like
‘<code>command not found</code>’, then you should look at the documentation for the system
in which you installed Rust, to determine if Cargo is separate.</p>
<h2>Converting to Cargo</h2>
<p>Let’s convert the Hello World program to Cargo. To Cargo-fy a project, you need
to do three things:</p>
<ol>
<li>Put your source file in the right directory.</li>
<li>Get rid of the old executable (<code>main.exe</code> on Windows, <code>main</code> everywhere else)
and make a new one.</li>
<li>Make a Cargo configuration file.</li>
</ol>
<p>Let's get started!</p>
<h3>Creating a new Executable and Source Directory</h3>
<p>First, go back to your terminal, move to your <em>hello_world</em> directory, and
enter the following commands:</p>
<pre><code class="language-bash">$ mkdir src
$ mv main.rs src/main.rs
$ rm main # or 'del main.exe' on Windows
</code></pre>
<p>Cargo expects your source files to live inside a <em>src</em> directory, so do that
first. This leaves the top-level project directory (in this case,
<em>hello_world</em>) 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.</p>
<p>Now, copy <em>main.rs</em> to the <em>src</em> directory, and delete the compiled file you
created with <code>rustc</code>. As usual, replace <code>main</code> with <code>main.exe</code> if you're on
Windows.</p>
<p>This example retains <code>main.rs</code> as the source filename because it's creating an
executable. If you wanted to make a library instead, you'd name the file
<code>lib.rs</code>. This convention is used by Cargo to successfully compile your
projects, but it can be overridden if you wish.</p>
<h3>Creating a Configuration File</h3>
<p>Next, create a new file inside your <em>hello_world</em> directory, and call it
<code>Cargo.toml</code>.</p>
<p>Make sure to capitalize the <code>C</code> in <code>Cargo.toml</code>, or Cargo won't know what to do
with the configuration file.</p>
<p>This file is in the <em><a href="https://github.com/toml-lang/toml">TOML</a></em> (Tom's Obvious, Minimal Language) format. TOML is
similar to INI, but has some extra goodies, and is used as Cargo’s
configuration format.</p>
<p>Inside this file, type the following information:</p>
<pre><code class="language-toml">[package]
name = &quot;hello_world&quot;
version = &quot;0.1.0&quot;
authors = [ &quot;Your name &lt;you@example.com&gt;&quot; ]
</code></pre>
<p>The first line, <code>[package]</code>, 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.</p>
<p>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.</p>
<p>Once you've added this information to the <em>Cargo.toml</em> file, save it to finish
creating the configuration file.</p>
<h2>Building and Running a Cargo Project</h2>
<p>With your <em>Cargo.toml</em> 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:</p>
<pre><code class="language-bash">$ cargo build
Compiling hello_world v0.1.0 (file:///home/yourname/projects/hello_world)
$ ./target/debug/hello_world
Hello, world!
</code></pre>
<p>Bam! If all goes well, <code>Hello, world!</code> should print to the terminal once more.</p>
<p>You just built a project with <code>cargo build</code> and ran it with
<code>./target/debug/hello_world</code>, but you can actually do both in one step with
<code>cargo run</code> as follows:</p>
<pre><code class="language-bash">$ cargo run
Running `target/debug/hello_world`
Hello, world!
</code></pre>
<p>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:</p>
<pre><code class="language-bash">$ cargo run
Compiling hello_world v0.1.0 (file:///home/yourname/projects/hello_world)
Running `target/debug/hello_world`
Hello, world!
</code></pre>
<p>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.</p>
<p>With simple projects, Cargo doesn't bring a whole lot over just using <code>rustc</code>,
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 <code>cargo build</code>, and it should work the right way.</p>
<h2>Building for Release</h2>
<p>When your project is finally ready for release, you can use <code>cargo build --release</code> 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.</p>
<p>Running this command also causes Cargo to create a new file called
<em>Cargo.lock</em>, which looks like this:</p>
<pre><code class="language-toml">[root]
name = &quot;hello_world&quot;
version = &quot;0.1.0&quot;
</code></pre>
<p>Cargo uses the <em>Cargo.lock</em> file to keep track of dependencies in your
application. This is the Hello World project's <em>Cargo.lock</em> 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.</p>
<p>That’s it! If you've been following along, you should have successfully built
<code>hello_world</code> with Cargo.</p>
<p>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:</p>
<pre><code class="language-bash">$ git clone someurl.com/foo
$ cd foo
$ cargo build
</code></pre>
<h2>Making A New Cargo Project the Easy Way</h2>
<p>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.</p>
<p>To start a new project with Cargo, enter <code>cargo new</code> at the command line:</p>
<pre><code class="language-bash">$ cargo new hello_world --bin
</code></pre>
<p>This command passes <code>--bin</code> because the goal is to get straight to making an
executable application, as opposed to a library. Executables are often called
<em>binaries</em> (as in <code>/usr/bin</code>, if you’re on a Unix system).</p>
<p>Cargo has generated two files and one directory for us: a <code>Cargo.toml</code> and a
<em>src</em> directory with a <em>main.rs</em> file inside. These should look familliar,
they’re exactly what we created by hand, above.</p>
<p>This output is all you need to get started. First, open <code>Cargo.toml</code>. It should
look something like this:</p>
<pre><code class="language-toml">[package]
name = &quot;hello_world&quot;
version = &quot;0.1.0&quot;
authors = [&quot;Your Name &lt;you@example.com&gt;&quot;]
</code></pre>
<p>Cargo has populated <em>Cargo.toml</em> with reasonable defaults based on the arguments
you gave it and your <code>git</code> global configuration. You may notice that Cargo has
also initialized the <code>hello_world</code> directory as a <code>git</code> repository.</p>
<p>Here’s what should be in <code>src/main.rs</code>:</p>
<pre><code class="language-rust">fn main() {
println!(&quot;Hello, world!&quot;);
}
</code></pre>
<p>Cargo has generated a &quot;Hello World!&quot; for you, and you’re ready to start coding!</p>
<blockquote>
<p>Note: If you want to look at Cargo in more detail, check out the official <a href="http://doc.crates.io/guide.html">Cargo
guide</a>, which covers all of its features.</p>
</blockquote>
<h1>The Design of Rust</h1>
<h1>Up and Running</h1>
<p>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.</p>
<p>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.</p>
<h1>Variable Bindings</h1>
<p>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.</p>
<h2>The basics of bindings</h2>
<p>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:</p>
<pre><code class="language-bash">$ cargo new --bin bindings
$ cd bindings
</code></pre>
<p>This creates a new project, ‘bindings’, and sets up our <code>Cargo.toml</code> and
<code>src/main.rs</code> files. As we saw in “Hello, World!”, Cargo will generate these
files and create a little ‘hello world’ program for us:</p>
<pre><code class="language-rust">fn main() {
println!(&quot;Hello, world!&quot;);
}
</code></pre>
<p>Let’s replace that program with this one:</p>
<pre><code class="language-rust">fn main() {
let x = 5;
println!(&quot;The value of x is: {}&quot;, x);
}
</code></pre>
<p>And finally, run it:</p>
<pre><code class="language-bash">$ cargo run
Compiling bindings v0.1.0 (file:///projects/bindings)
Running `target/debug/bindings`
The value of x is: 5
</code></pre>
<p>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.</p>
<pre><code class="language-rust,ignore">fn main() {
</code></pre>
<p>The <code>main()</code> 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, <code>{</code>, indicates the
start of the function’s body.</p>
<pre><code class="language-rust,ignore"> let x = 5;
</code></pre>
<p>This is our first ‘variable binding’, which we create with a ‘<code>let</code> statement’.</p>
<p>This <code>let</code> statement has this form:</p>
<pre><code class="language-text">let NAME = EXPRESSION;
</code></pre>
<p>A <code>let</code> statement first evaluates the <code>EXPRESSION</code>, and then binds the
resulting value to <code>NAME</code> 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:</p>
<pre><code class="language-rust">let x = 2 + 3;
</code></pre>
<p>In general, <code>let</code> 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.</p>
<p>Before we do that, though, let’s finish investigating this example. Here’s the
next line:</p>
<pre><code class="language-rust,ignore"> println!(&quot;The value of x is: {}&quot;, x);
</code></pre>
<p>The <code>println!</code> macro prints text to the screen. We can tell that it’s a macro
due to the <code>!</code>. 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 <code>!</code>, remember that it signifies a macro. Macros can add new
syntax to the language, and the <code>!</code> is a reminder that things may look slightly
unusual.</p>
<p><code>println!</code>, specifically, has one required argument, a ‘format string’, and
zero or more optional arguments. The format string can contain the special text
<code>{}</code>. Each instance of <code>{}</code> corresponds to an additional argument. Here’s an
example:</p>
<pre><code class="language-rust">let x = 2 + 3;
let y = x + 5;
println!(&quot;The value of x is {}, and the value of y is {}&quot;, x, y);
</code></pre>
<p>You can think of <code>{}</code> as little crab pincers, holding the value in place. This
placeholder has a number of more advanced formatting options that we’ll discuss
later.</p>
<pre><code class="language-rust,ignore">}
</code></pre>
<p>Finally, a closing curly brace matches up with the opening curly brace that
declared the <code>main()</code> function, and declares its end.</p>
<p>This explains our output:</p>
<pre><code class="language-text">The value of x is: 5
</code></pre>
<p>We assign <code>5</code> to a binding, <code>x</code>, and then print it to the screen with
<code>println!</code>.</p>
<h2>Multiple binding</h2>
<p>Let’s try a more complex pattern. Change our example program to this:</p>
<pre><code class="language-rust">fn main() {
let (x, y) = (5, 6);
println!(&quot;The value of x is: {}&quot;, x);
println!(&quot;The value of y is: {}&quot;, y);
}
</code></pre>
<p>And run it with <code>cargo run</code>:</p>
<pre><code class="language-text">$ 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
</code></pre>
<p>We’ve created two bindings with one <code>let</code>! Here’s our pattern:</p>
<pre><code class="language-text">(x, y)
</code></pre>
<p>And here’s the value:</p>
<pre><code class="language-text">(5, 6)
</code></pre>
<p>As you can see, the two line up visually, and so <code>let</code> binds <code>5</code> to <code>x</code> and <code>6</code>
to <code>y</code>. We could have used two <code>let</code> statements as well:</p>
<pre><code class="language-rust">fn main() {
let x = 5;
let y = 6;
}
</code></pre>
<p>In simple cases like this, two <code>let</code>s 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.</p>
<h2>Type annotations</h2>
<p>You may have noticed that we didn’t declare the type of <code>x</code> or <code>y</code> in our
previous examples. Rust is a <em>statically typed</em> 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.</p>
<p>The primary way that the type is inferred is by looking at how it is used.
Let’s look at the example again:</p>
<pre><code class="language-rust">fn main() {
let x = 5;
}
</code></pre>
<p>When we bind <code>x</code> to <code>5</code>, the compiler knows that <code>x</code> should be a numeric type.
Without any other information, it defaults to <code>i32</code>, a thirty-two bit integer
type. We’ll talk more about Rust’s basic types in section 3.3.</p>
<p>Here’s what a <code>let</code> statement with a ‘type annotation’ looks like:</p>
<pre><code class="language-rust">fn main() {
let x: i32 = 5;
}
</code></pre>
<p>We can add a colon, followed by the type name. Here’s the structure of a <code>let</code>
statement with a type annotation:</p>
<pre><code class="language-text">let PATTERN: TYPE = VALUE;
</code></pre>
<p>Note that the colon and the <code>TYPE</code> go <em>after</em> the <code>PATTERN</code>, not in the pattern
itself. As an example, here’s our more complex pattern with two bindings:</p>
<pre><code class="language-rust">fn main() {
let (x, y): (i32, i32) = (5, 6);
}
</code></pre>
<p>Just like we match up the <code>VALUE</code> with the <code>PATTERN</code>, we match up the <code>TYPE</code>
with the <code>PATTERN</code>.</p>
<h2>Delayed Initialization</h2>
<p>We do not have to provide bindings with an initial value, and can assign it
later. Try this program:</p>
<pre><code class="language-rust">fn main() {
let x;
x = 5;
println!(&quot;The value of x is: {}&quot;, x);
}
</code></pre>
<p>And run it with <code>cargo run</code>:</p>
<pre><code class="language-text">$ cargo run
Compiling bindings v0.1.0 (file:///projects/bindings)
Running `target/debug/bindings`
The value of x is: 5
</code></pre>
<p>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:</p>
<pre><code class="language-rust,ignore">fn main() {
let x;
println!(&quot;The value of x is: {}&quot;, x);
x = 5;
}
</code></pre>
<p>We can find out the answer with <code>cargo run</code>:</p>
<pre><code class="language-text"> 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);
^
&lt;std macros&gt;:2:25: 2:56 note: in this expansion of format_args!
&lt;std macros&gt;:3:1: 3:54 note: in this expansion of print! (defined in &lt;std macros&gt;)
src/main.rs:4:5: 4:42 note: in this expansion of println! (defined in &lt;std macros&gt;)
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.
</code></pre>
<p>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 <code>x</code>.</p>
<h3>Extended error explanations</h3>
<p>There’s one more interesting part of this error message:</p>
<pre><code class="language-text">src/main.rs:4:39: 4:40 help: run `rustc --explain E0381` to see a detailed explanation
</code></pre>
<p>We can see an extended explanation by passing the <code>--explain</code> flag to <code>rustc</code>.
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 <code>E0381</code>:</p>
<pre><code class="language-bash">$ 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.
</code></pre>
<p>These explanations can really help if you’re stuck on an error. The compiler is
your friend, and is here to help.</p>
<h2>Mutable bindings</h2>
<p>What about changing the value of a binding? Here’s another sample program that
asks this question:</p>
<pre><code class="language-rust,ignore">fn main() {
let x = 5;
x = 6;
println!(&quot;The value of x is: {}&quot;, x);
}
</code></pre>
<p><code>cargo run</code> has the answer for us:</p>
<pre><code class="language-bash">$ 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;
^
</code></pre>
<p>The error mentions <code>re-assigment of immutable variable</code>. 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 <code>mut</code> in front to make the binding a mutable
one. Here’s an example:</p>
<pre><code class="language-rust">fn main() {
let mut x = 5;
println!(&quot;The value of x is: {}&quot;, x);
x = 6;
println!(&quot;The value of x is: {}&quot;, x);
}
</code></pre>
<p>Running this, we get:</p>
<pre><code class="language-bash">$ 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
</code></pre>
<p>We can now change the value that <code>x</code> binds to. Note that the syntax is not <code>let mut</code> exactly; it’s using <code>mut</code> in a pattern. This becomes more obvious with our
<code>()</code> pattern:</p>
<pre><code class="language-rust,ignore">fn main() {
let (mut x, y) = (5, 6);
x = 7;
y = 8;
}
</code></pre>
<p>The compiler will complain about this program:</p>
<pre><code class="language-bash">$ 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);
^
</code></pre>
<p>It’s fine with re-assigning <code>x</code>, but not <code>y</code>. The <code>mut</code> only applies to the
name that follows it, not the whole pattern.</p>
<h3>Reassignment, not mutation</h3>
<p>There is one subtlety we haven’t covered yet: <code>mut</code> allows you to mutate <em>the
binding</em>, but not <em>what the binding binds to</em>. In other words:</p>
<pre><code class="language-rust">fn main() {
let mut x = 5;
x = 6;
}
</code></pre>
<p>This is not changing the value that <code>x</code> is bound to, but creating a new value,
<code>6</code>, 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.</p>
<h2>Scope</h2>
<p>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:</p>
<pre><code class="language-rust">fn main() {
println!(&quot;x is not yet in scope&quot;);
let x = 5;
println!(&quot;x is now in scope&quot;);
println!(&quot;In real code, we’d now do a bunch of work.&quot;);
println!(&quot;x will go out of scope now! The next curly brace is ending the main function.&quot;);
}
</code></pre>
<p>We can create arbitrary scopes through the use of <code>{</code> and <code>}</code>:</p>
<pre><code class="language-rust">fn main() {
println!(&quot;x is not yet in scope&quot;);
let x = 5;
println!(&quot;x is now in scope&quot;);
println!(&quot;Let’s start a new scope!&quot;);
{
let y = 5;
println!(&quot;y is now in scope&quot;);
println!(&quot;x is also still in scope&quot;);
println!(&quot;y will go out of scope now!&quot;);
println!(&quot;The next curly brace is ending the scope we started.&quot;);
}
println!(&quot;x is still in scope, but y is now out of scope and is not usable&quot;);
println!(&quot;x will go out of scope now! The next curly brace is ending the main function.&quot;);
}
</code></pre>
<p>What bindings are in and out of scope will become much more important later,
once we learn about ‘references’ and ‘traits’.</p>
<h2>Shadowing</h2>
<p>A final thing about bindings: they can ‘shadow’ previous bindings with the same
name. Here’s a sample program:</p>
<pre><code class="language-rust">fn main() {
let x = 5;
let x = 6;
println!(&quot;The value of x is: {}&quot;, x);
}
</code></pre>
<p>Running it, we can see the shadowing in action:</p>
<pre><code class="language-text">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
</code></pre>
<p>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 <code>x</code> is <code>6</code>. But
we didn’t declare <code>x</code> as mutable. Instead, we declared a <em>new</em> binding that is
<em>also</em> named <code>x</code>, and gave it a new value. The older value that we bound <code>x</code> to
is inaccessible as soon as the new <code>x</code> is declared. This can be useful if you’d
like to perform a few transformations on a value, and leave it immutable. For
example:</p>
<pre><code class="language-rust">fn main() {
let x = 5;
let x = x + 1;
let x = x * 2;
println!(&quot;The value of x is: {}&quot;, x);
}
</code></pre>
<p>This will print:</p>
<pre><code class="language-bash"> Compiling bindings v0.1.0 (file:///projects/bindings)
Running `target/debug/bindings`
The value of x is: 12
</code></pre>
<p>This lets us modify <code>x</code>, 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 <code>12</code>, we don’t want to modify <code>x</code> again. If we
had written this program in a mutable style, like this:</p>
<pre><code class="language-rust">fn main() {
let mut x = 5;
x = x + 1;
x = x * 2;
println!(&quot;The value of x is: {}&quot;, x);
x = 15;
println!(&quot;The value of x is: {}&quot;, x);
}
</code></pre>
<p>Rust is happy to let us mutate it again, to <code>15</code>. A similar program in our
immutable style will let us know about that accidental mutation, however:</p>
<pre><code class="language-rust,ignore">fn main() {
let x = 5;
let x = x + 1;
let x = x * 2;
println!(&quot;The value of x is: {}&quot;, x);
x = 15;
println!(&quot;The value of x is: {}&quot;, x);
}
</code></pre>
<p>If we try to compile, we get an error:</p>
<pre><code class="language-bash">$ 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`.
</code></pre>
<p>Exactly what we wanted.</p>
<p>Shadowing can take some time to get used to, but it’s very powerful, and works
well with immutability.</p>
<p>There was one more thing we should talk about in the output from compiling our
initial program. It’s this part:</p>
<pre><code class="language-text">src/main.rs:2:9: 2:10 warning: unused variable: `x`, #[warn(unused_variables)] on by default
</code></pre>
<p>Here’s the two lines of relevant code:</p>
<pre><code class="language-rust">let x = 5;
let x = 6;
</code></pre>
<p>Rust knows that we shadowed <code>x</code>, but we never ended up using the initial value.
This isn’t <em>wrong</em>, exactly, it just may not have been what we wanted. In this
case, the compiler issues a ‘warning’, but still compiles our program. The
<code>#[warn(unused_variables)]</code> 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 <code>x</code>.</p>
<h3>Shadowing and scopes</h3>
<p>Like any binding, a binding that shadows another binding will go away at the
end of a scope. Here’s an example program:</p>
<pre><code class="language-rust">fn main() {
let x = 5;
println!(&quot;Before shadowing, x is: {}&quot;, x);
{
let x = 6;
println!(&quot;Now that x is shadowed, x is: {}&quot;, x);
}
println!(&quot;After shadowing, x is: {}&quot;, x);
}
</code></pre>
<p>If we run this example, we can see the shadow appear and disappear:</p>
<pre><code class="language-bash">$ 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
</code></pre>
<h1>Functions</h1>
<p>Functions are pervasive in Rust code. We’ve already seen the most important
function, <code>main()</code>, in previous sections of the book:</p>
<pre><code class="language-rust">fn main() {
println!(&quot;Hello, world!&quot;);
}
</code></pre>
<p>We can declare new functions with the <code>fn</code> keyword:</p>
<pre><code class="language-rust">fn another_function() {
println!(&quot;Another function.&quot;);
}
</code></pre>
<p>Rust code uses <code>snake_case</code> 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:</p>
<pre><code class="language-rust">fn main() {
println!(&quot;Hello, world!&quot;);
another_function();
}
fn another_function() {
println!(&quot;Another function.&quot;);
}
</code></pre>
<p>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:</p>
<pre><code class="language-bash">$ cargo new --bin functions
$ cd functions
</code></pre>
<p>Place the new example in <code>src/main.rs</code>, and run it:</p>
<pre><code class="language-bash">$ cargo run
Compiling functions v0.1.0 (file:///projects/functions)
Running `target/debug/functions`
Hello, world!
Another function.
</code></pre>
<p>As we can see, the lines execute in order: first, we print out our “Hello,
world!” message, and then <code>another_function()</code> is called. It then prints its
message as well.</p>
<h2>Function Arguments</h2>
<p>Functions can also take arguments:</p>
<pre><code class="language-rust">fn main() {
another_function(5);
}
fn another_function(x: i32) {
println!(&quot;The value of x is: {}&quot;, x);
}
</code></pre>
<p>Let’s try running it:</p>
<pre><code class="language-bash">$ cargo run
Compiling functions v0.1.0 (file:///projects/functions)
Running `target/debug/functions`
The value of x is: 5
</code></pre>
<p>Let’s take a closer look at <code>another_function()</code>’s signature:</p>
<pre><code class="language-rust,ignore">fn another_function(x: i32) {
</code></pre>
<p>Declaring a function which takes a single argument looks like this:</p>
<pre><code class="language-text">fn NAME(PATTERN: TYPE) {
</code></pre>
<p>That’s right, patterns appear again. Consider how the parameter declaration
here looks like the <code>let</code> bindings we used earlier:</p>
<pre><code class="language-rust,ignore">let x: i32;
fn another_function(x: i32) {
</code></pre>
<p>There’s only one difference here: in function signatures, we <em>must</em> 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.</p>
<p>You can separate multiple arguments with a comma:</p>
<pre><code class="language-text">fn NAME(PATTERN, PATTERN, PATTERN, PATTERN...) {
</code></pre>
<p>Here’s a full example:</p>
<pre><code class="language-rust">fn main() {
another_function(5, 6);
}
fn another_function(x: i32, y: i32) {
println!(&quot;The value of x is: {}&quot;, x);
println!(&quot;The value of y is: {}&quot;, y);
}
</code></pre>
<p>Let’s try it:</p>
<pre><code class="language-bash">$ 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
</code></pre>
<p>We could also create bindings, and pass them in as arguments:</p>
<pre><code class="language-rust">fn main() {
let a = 5;
let b = 6;
another_function(a, b);
}
fn another_function(x: i32, y: i32) {
println!(&quot;The value of x is: {}&quot;, x);
println!(&quot;The value of y is: {}&quot;, y);
}
</code></pre>
<p>This has the same effect:</p>
<pre><code class="language-bash">$ 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
</code></pre>
<p>Note that our bindings are called <code>a</code> and <code>b</code>, yet inside of the function, we
refer to them by the names in the signature, <code>x</code> and <code>y</code>. 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.</p>
<h2>Return values</h2>
<p>Functions can also return values back to the function that called them:</p>
<pre><code class="language-TEXT">fn NAME(PATTERN, PATTERN, PATTERN, PATTERN...) -&gt; TYPE {
</code></pre>
<p>We don’t name return values, but we do declare their type, after an arrow:
<code>-&gt;</code>. Here’s a sample program:</p>
<pre><code class="language-rust">fn main() {
let x = five();
println!(&quot;The value of x is: {}&quot;, x);
}
fn five() -&gt; i32 {
5
}
</code></pre>
<p>Let’s try running it:</p>
<pre><code class="language-bash">$ cargo run
Compiling functions v0.1.0 (file:///projects/functions)
Running `target/debug/functions`
The value of x is: 5
</code></pre>
<p>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:</p>
<pre><code class="language-rust,ignore">let x = five();
</code></pre>
<p>Because <code>five()</code> returns a <code>5</code>, this is the same as:</p>
<pre><code class="language-rust">let x = 5;
</code></pre>
<p>The second interesting bit is <code>five()</code> itself:</p>
<pre><code class="language-rust">fn five() -&gt; i32 {
5
}
</code></pre>
<p>We have no arguments, and our return type, <code>i32</code>. However, the body of this
function is a lonely <code>5</code>. 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?</p>
<p>The answer to this question is:</p>
<blockquote>
<p>The return value of a function is the value of its final expression.</p>
</blockquote>
<p>We haven’t talked about expressions yet, so this definition doesn’t help a lot.
Let’s go over that now.</p>
<h2>Statements and Expressions</h2>
<p>Expressions are bits of code that evaluate to a value. Consider some math
operations, like this:</p>
<pre><code class="language-rust,ignore">5 + 6
</code></pre>
<p>We can evaluate this expression, and come up with a value: <code>11</code>. In Rust, most
bits of code are expressions. For example, calling a function is an expression:</p>
<pre><code class="language-rust,ignore">foo(5)
</code></pre>
<p>The value is equal to whatever the return value of <code>foo()</code> is.</p>
<p>So why does this matter? Well, not everything is an expression. Some things are
‘statements’. Expressions <em>compute</em> something, but statements <em>bind</em> or <em>do</em>
something. It’s a subtle difference. We’ve already seen two kinds of
statements: <code>let</code> statements, and <code>fn</code> declarations.</p>
<p>Because <code>let</code> is a statement, not an expression, you can’t assign it to another
binding. Here’s an example that doesn’t work:</p>
<pre><code class="language-rust,ignore">fn main() {
let x = (let y = 6);
}
</code></pre>
<p>If we try to run this program, we’ll get an error:</p>
<pre><code class="language-bash">$ 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`.
</code></pre>
<p>We also cannot somehow assign a <code>fn</code> declaration to a binding, either.</p>
<p>So what’s this have to do with return values? Well, <code>{}</code>, a ‘block’ that we
used earlier to create new scopes, <em>is</em> an expression. Let’s take a closer look
at <code>{}</code>. It looks like this:</p>
<pre><code class="language-text">{
STATEMENT*
EXPRESSION
}
</code></pre>
<p>The <code>*</code> 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
<code>let</code> statements:</p>
<pre><code class="language-rust">fn main() {
let x = 5;
let y = {
let z = 1;
x + z + 5
};
println!(&quot;The value of y is: {}&quot;, y);
}
</code></pre>
<p>Let’s try running this program:</p>
<pre><code class="language-bash"> Compiling functions v0.1.0 (file:///projects/functions)
Running `target/debug/functions`
The value of y is: 11
</code></pre>
<p>We’re now using a block to give us a value for <code>y</code>:</p>
<pre><code class="language-rust,ignore">let y = {
};
</code></pre>
<p>Since the block can contain statements, we create a new variable binding, <code>z</code>,
and give it a value. We then do some math for the final expression of the
block:</p>
<pre><code class="language-rust,ignore">{
let z = 1;
x + z + 5
}
</code></pre>
<p><code>5 + 1 + 5</code> is <code>11</code>, and so the value of the entire block is <code>11</code>. This gets
substituted into our <code>let</code> statement for <code>y</code>:</p>
<pre><code class="language-rust,ignore">let y = 11;
</code></pre>
<p>Hence our output saying <code>y</code> is <code>11</code>.</p>
<p>Where else do we use blocks? As the body of functions! They’re very similar:</p>
<pre><code class="language-rust">fn main() {
let x = 5;
let y = {
x + 1
};
println!(&quot;The value of y is: {}&quot;, y);
let y = plus_one(x);
println!(&quot;The value of y is: {}&quot;, y);
}
fn plus_one(x: i32) -&gt; i32 {
x + 1
}
</code></pre>
<p>Running this gives:</p>
<pre><code class="language-bash">$ 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
</code></pre>
<p>In both cases, we use a block to produce a value. In the first case, it’s
assigning with <code>let</code>:</p>
<pre><code class="language-rust,ignore">let y = {
</code></pre>
<p>In the second, it’s the return value of the function:</p>
<pre><code class="language-rust,ignore">fn plus_one(x: i32) -&gt; i32 {
</code></pre>
<h3>Expression statements</h3>
<p>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 <code>plus_one()</code>:</p>
<pre><code class="language-rust,ignore">fn main() {
let x = plus_one(5);
println!(&quot;The value of x is: {}&quot;, x);
}
fn plus_one(x: i32) -&gt; i32 {
x + 1;
}
</code></pre>
<p>Instead of an expression, <code>x + 1</code>, we’ve now turned it into a statement,
<code>x + 1;</code>.</p>
<p>Running this gives an error:</p>
<pre><code class="language-bash">$ 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) -&gt; 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`.
</code></pre>
<p>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 <code>i32</code>.</p>
<p>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.</p>
<h2>Multiple return values</h2>
<p>Functions cannot directly return multiple values. There’s a trick, however.
Remember the <code>()</code>s we used when showing off complex bindings?</p>
<pre><code class="language-rust">fn main() {
let (x, y) = (5, 6);
}
</code></pre>
<p>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:</p>
<pre><code class="language-rust">fn main() {
let (x, y) = two_numbers();
println!(&quot;The value of x is: {}&quot;, x);
println!(&quot;The value of y is: {}&quot;, y);
}
fn two_numbers() -&gt; (i32, i32) {
(5, 6)
}
</code></pre>
<p>Running this will show us the values:</p>
<pre><code class="language-bash">$ 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
</code></pre>
<p>There are two interesting changes here: assigning the return value of
<code>two_numbers()</code> to <code>x</code> and <code>y</code>, and the declaration of <code>two_numbers()</code> itself.</p>
<p>Let’s look at the declaration first:</p>
<pre><code class="language-rust">fn two_numbers() -&gt; (i32, i32) {
(5, 6)
}
</code></pre>
<p>The <code>(i32, i32)</code> should look familiar. We saw it in <code>let</code> bindings earlier:</p>
<pre><code class="language-rust">let (x, y): (i32, i32) = (5, 6);
</code></pre>
<p>The <code>(i32, i32)</code> syntax says “a tuple with two <code>i32</code>s in it.” The <code>(5, 6)</code>
syntax creates a new one, with <code>5</code> and <code>6</code>.</p>
<p>This tuple is then returned, and assigned to <code>x</code> and <code>y</code>:</p>
<pre><code class="language-rust,ignore">let (x, y) = two_numbers();
</code></pre>
<p>See how all these bits fit together?</p>
<p>We call this behavior of <code>let</code> ‘destructuring’, because it takes the structure
of the expression that comes after the <code>=</code> and takes it apart.</p>
<h1>Scalar Types</h1>
<p>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.</p>
<p>Remember, you can rely on type inference to figure out the type of a binding,
or you can annotate it explicitly:</p>
<pre><code class="language-rust">fn main() {
let x: i32 = 5;
}
</code></pre>
<h2>Integers</h2>
<p>You’ve already seen one primitive type: <code>i32</code>. There are a number of built-in
number types in Rust.</p>
<p>Here’s a chart of Rust’s integer types:</p>
<table><thead><tr><td> </td><td> signed </td><td> unsigned </td></tr></thead>
<tr><td> 8-bit </td><td> i8 </td><td> u8 </td></tr>
<tr><td> 16-bit </td><td> i16 </td><td> u16 </td></tr>
<tr><td> 32-bit </td><td> i32 </td><td> u32 </td></tr>
<tr><td> 64-bit </td><td> i64 </td><td> u64 </td></tr>
<tr><td> arch </td><td> isize </td><td> usize </td></tr>
</table>
<p>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.</p>
<p>Finally, <code>isize</code> and <code>usize</code> 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.</p>
<p>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 <code>i32</code>. The primary use
case for <code>isize</code>/<code>usize</code> is when indexing some sort of collection. We’ll talk
more about our first collection, arrays, in just a moment.</p>
<h2>Floating-point numbers</h2>
<p>Rust also has two primitive floating-point numbers: <code>f32</code> and <code>f64</code>. They are
32 bits and 64 bits in size, respectively. The default is <code>f64</code>.</p>
<pre><code class="language-rust">fn main() {
let x = 2.0; // f64
let y: f32 = 3.0; // f32
}
</code></pre>
<p>Floating-point numbers are represented according to the IEEE-754 standard.
<code>f32</code> is a single-precision float, <code>f64</code> is double-precision.</p>
<h2>Numeric operations</h2>
<p>Rust supports the usual operations you’d expect on all of these number types:</p>
<pre><code class="language-rust">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;
}
</code></pre>
<h2>Booleans</h2>
<p>Somewhat fundamental to all computing, Rust has a boolean type, <code>bool</code>, with
two possible values:</p>
<pre><code class="language-rust">fn main() {
let t = true;
let f: bool = false; // with explict type annotation
}
</code></pre>
<p>The main way to consume boolean values is through conditionals like <code>if</code>, which
we’ll see later in the chapter.</p>
<h2>Characters</h2>
<p>We’ve only worked with numbers so far, but what about letters? Rust’s most
primitive alphabetic type is the <code>char</code>:</p>
<pre><code class="language-rust">fn main() {
let c = 'z';
let z = 'ℤ';
}
</code></pre>
<p>Rust’s <code>char</code> represents a <a href="http://www.unicode.org/glossary/#unicode_scalar_value">Unicode Scalar Value</a>, 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 <code>char</code>. It also means that <code>char</code>s are four bytes each.</p>
<h1>Compound Types</h1>
<p>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.</p>
<h2>Tuples</h2>
<p>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.</p>
<p>We create a tuple by writing a comma-separated list of values inside
parentheses; each position in the tuple has a distinct type:</p>
<pre><code class="language-rust">fn main() {
let tup: (i32, f64, u8) = (500, 6.4, 1);
}
</code></pre>
<p>Note that, unlike the examples of multiple bindings, here we bound the
single name <code>tup</code> to the entire tuple. We can then use pattern
matching to destructure this tuple value:</p>
<pre><code class="language-rust">fn main() {
let tup: (i32, f64, u8) = (500, 6.4, 1);
let (x, y, z) = tup;
println!(&quot;The value of y is: {}&quot;, y);
}
</code></pre>
<p>Tuples are used sparingly in Rust code. This is because the elements of a tuple
are anonymous, which can make code hard to read.</p>
<h3>Tuple indexing</h3>
<p>In addition to destructuring through pattern matching, we can also access a
tuple element directly using <code>.</code>, followed by the index we want to access:</p>
<pre><code class="language-rust">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;
}
</code></pre>
<p>As you can see, the first index is <code>0</code>.</p>
<h3>Single-element tuples</h3>
<p>There’s one last trick with tuples: <code>(5)</code> is actually ambiguous: is it a tuple,
or is it a <code>5</code> in parethesis? If you need to disambiguate, use a comma:</p>
<pre><code class="language-rust">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.
}
</code></pre>
<h2>Arrays</h2>
<p>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:</p>
<pre><code class="language-rust">fn main() {
let a = [1, 2, 3, 4, 5];
}
</code></pre>
<p>An array’s type consists of the type of the elements it contains, as well as
the length:</p>
<pre><code class="language-rust">fn main() {
let a: [i32; 5] = [1, 2, 3, 4, 5];
}
</code></pre>
<p>An array is a single chunk of memory, allocated on the stack.</p>
<p>We can access elements of an array using indexing:</p>
<pre><code class="language-rust">fn main() {
let a = [1, 2, 3, 4, 5];
let first = a[0];
let second = a[1];
}
</code></pre>
<p>In this example, <code>first</code> will hold the value <code>1</code>, and <code>second</code> will be bound to
<code>2</code>. 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:</p>
<pre><code class="language-rust">fn main() {
let mut a = [1, 2, 3, 4, 5];
let first = a[0];
a[0] = 7;
println!(&quot;The value of first is: {}&quot;, first);
}
</code></pre>
<p>Running this example will show that <code>first</code> is still <code>1</code>. 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.</p>
<p>One last thing: now that we are modifying the array, <code>a</code> needs to be declared
<code>mut</code>.</p>
<p>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 <code>panic!</code> macro, and a
new way of printing things: <code>Debug</code>.</p>
<h3>Panic</h3>
<p>We showed what happens when you access elements of an array, but what if we
give an invalid index?</p>
<pre><code class="language-rust,should_panic">fn main() {
let a = [1, 2, 3, 4, 5];
let invalid = a[10];
println!(&quot;The value of invalid is: {}&quot;, invalid);
}
</code></pre>
<p>If we run this example, we will get an error. Let’s re-use our <code>functions</code>
project from before. Change your <code>src/main.rs</code> to look like the example, and
run it:</p>
<pre><code class="language-bash">$ cargo run
Compiling functions v0.1.0 (file:///projects/functions)
Running `target/debug/functions`
thread ‘&lt;main&gt;’ 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)
</code></pre>
<p>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</p>
<ol start="10">
<li></li>
</ol>
<p>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.</p>
<p>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.</p>
<h3>Debug</h3>
<p>So far, we’ve been printing values using <code>{}</code>. If we try that with an array,
though...</p>
<pre><code class="language-rust,ignore">fn main() {
let a = [1, 2, 3, 4, 5];
println!(&quot;a is: {}&quot;, a);
}
</code></pre>
<p>... we will get an error:</p>
<pre><code class="language-bash">$ 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);
^
&lt;std macros&gt;:2:25: 2:56 note: in this expansion of format_args!
&lt;std macros&gt;:3:1: 3:54 note: in this expansion of print! (defined in &lt;std macros&gt;)
src/main.rs:4:5: 4:28 note: in this expansion of println! (defined in &lt;std macros&gt;)
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
</code></pre>
<p>Whew! The core of the error is this part: the trait <code>core::fmt::Display</code> 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: <code>println!</code> can do many kinds of formatting.
By default, <code>{}</code> implements a kind of formatting known as <code>Display</code>: output
intended for direct end-user consumption. The primitive types we’ve seen so far
implement <code>Display</code>, as there’s only one way you’d show a <code>1</code> to a user. But
with arrays, the output is less clear. Do you want commas or not? What about
the <code>[]</code>s?</p>
<p>Due to these questions, more complex types in the standard library do not
implement <code>Display</code> formatting. There is another kind of formatting, <code>Debug</code>,
which is a bit different: intended for programmer consumption. We can ask
<code>println!</code> to use <code>Debug</code> formatting with <code>:?</code>:</p>
<pre><code class="language-rust">fn main() {
let a = [1, 2, 3, 4, 5];
println!(&quot;a is {:?}&quot;, a);
}
</code></pre>
<p>This will work:</p>
<pre><code class="language-bash">$ cargo run
Compiling functions v0.1.0 (file:///projects/functions)
Running `target/debug/functions`
a is [1, 2, 3, 4, 5]
</code></pre>
<p>You’ll see this repeated later, with other types. And we’ll cover traits fully
later in the book, Section 9.</p>
<h1>Comments</h1>
<p>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’.</p>
<p>Here’s a comment:</p>
<pre><code class="language-rust">// Hello, world.
</code></pre>
<p>Comments start with two slashes, and last until the end of the line. Larger
comments will need more lines:</p>
<pre><code class="language-rust">// 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.
</code></pre>
<p>Comments can also go at the end of lines:</p>
<pre><code class="language-rust">fn main() {
let lucky_number = 7; // I’m feeling lucky today.
}
</code></pre>
<p>But you’ll more often see them above:</p>
<pre><code class="language-rust">fn main() {
// I’m feeling lucky today.
let lucky_number = 7;
}
</code></pre>
<p>That’s all there is to it. Comments are not particularly complicated.</p>
<h2>Documentation comments</h2>
<p>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 <code>rustdoc</code> tool that comes with Rust reads
documentation comments and produces HTML documentation from them.</p>
<p>Documentation comments use an extra slash:</p>
<pre><code class="language-rust">/// The foo function doesn’t really do much.
fn foo() {
}
/// We also can use
/// multiple comments here too,
/// like we did before
fn bar() {
}
</code></pre>
<p>This comment would then be interpreted by <code>rustdoc</code> as documenting the thing
that follows it: <code>foo()</code> and <code>bar()</code>.</p>
<p>Because documentation comments have semantic meaning to <code>rustdoc</code>, the compiler
will pay attention to the placement of your documentation comments. For
example, a program with only this:</p>
<pre><code class="language-rust,ignore">/// What am I documenting?
</code></pre>
<p>Will give a compiler error:</p>
<pre><code class="language-text">src/main.rs:1:1: 1:27 error: expected item after doc comment
src/main.rs:1 /// What am I documenting?
^~~~~~~~~~~~~~~~~~~~~~~~~~
</code></pre>
<h1>Control flow with <code>if</code></h1>
<blockquote>
<p>Two roads diverged in a yellow wood,<br />
And sorry I could not travel both<br />
And be one traveler, long I stood<br />
And looked down one as far as I could<br />
To where it bent in the undergrowth;</p>
<ul>
<li>Robert Frost, “The Road Not Taken”</li>
</ul>
</blockquote>
<p>In Rust, there are a few ways to cause our code to branch. The most fundamental
way is by using <code>if</code>. An <code>if</code> expression gives us two paths forward, and asks
the question, “Which one should I take?”</p>
<p>Let’s make a new project to explore <code>if</code>. Navigate to your projects directory,
and use Cargo to make a new project called <code>branches</code>:</p>
<pre><code class="language-bash">$ cargo new --bin branches
$ cd branches
</code></pre>
<p>Here’s a sample program using <code>if</code>:</p>
<pre><code class="language-rust">fn main() {
let condition = true;
if condition {
println!(&quot;condition was true&quot;);
} else {
println!(&quot;condition was false&quot;);
}
}
</code></pre>
<p>Let's try running it:</p>
<pre><code class="language-bash">$ cargo run
Compiling branches v0.1.0 (file:///projects/branches)
Running `target/debug/branches`
condition was true
</code></pre>
<p>We can change the value of <code>condition</code>:</p>
<pre><code class="language-rust"> let condition = false;
</code></pre>
<p>And then run it again:</p>
<pre><code class="language-bash">$ cargo run
Compiling branches v0.1.0 (file:///projects/branches)
Running `target/debug/branches`
condition was false
</code></pre>
<p>This is the very basic structure of <code>if</code>: <em>if</em> the condition is true, then
execute some code. If it’s not true, then execute some other code, after
<code>else</code>.</p>
<p>An <code>else</code> is not required:</p>
<pre><code class="language-rust">fn main() {
let condition = false;
if condition {
println!(&quot;condition was true&quot;);
}
}
</code></pre>
<p>In this case, nothing is printed.</p>
<p>It’s also worth noting that <code>condition</code> here <em>must</em> be a <code>bool</code>. Let’s try an
example with something else:</p>
<pre><code class="language-rust,ignore">fn main() {
let condition = 5;
if condition {
println!(&quot;condition was five&quot;);
}
}
</code></pre>
<p>If we try to run this program, Rust will complain:</p>
<pre><code class="language-bash"> 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`.
</code></pre>
<p>We expected a <code>bool</code>, but got an integer. Rust will not automatically try to convert non-boolean types to a boolean here. We must be explicit.</p>
<h2><code>else if</code></h2>
<p>We can make multiple decisions by combining <code>if</code> and <code>else</code> in another way:</p>
<pre><code class="language-rust">fn main() {
let number = 5;
if number == 3 {
println!(&quot;condition was 3&quot;);
} else if number == 4 {
println!(&quot;condition was 4&quot;);
} else if number == 5 {
println!(&quot;condition was 5&quot;);
} else {
println!(&quot;condition was something else&quot;);
}
}
</code></pre>
<p>Let's try running it:</p>
<pre><code class="language-bash">$ cargo run
Compiling branches v0.1.0 (file:///projects/branches)
Running `target/debug/branches`
condition was 5
</code></pre>
<p>When this program executes, it will check each <code>if</code> in turn, and execute the
first body for which the condition holds true.</p>
<p>Using a single <code>else if</code> 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 <code>match</code> for these cases. We'll cover it later, when we talk about <code>enums</code>.</p>
<h2><code>if</code> as an expression</h2>
<p>There’s one last detail we need to learn about <code>if</code>: it’s an expression. That means
that we can use it on the right hand side of a <code>let</code> binding, for instance:</p>
<pre><code class="language-rust">fn main() {
let condition = true;
let number = if condition {
5
} else {
6
};
println!(&quot;The value of number is: {}&quot;, number);
}
</code></pre>
<p>Let’s run this:</p>
<pre><code class="language-bash">$ cargo run
Compiling branches v0.1.0 (file:///projects/branches)
Running `target/debug/branches`
The value of number is: 5
</code></pre>
<p>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
<code>if</code> expression depends on which block of code executes.</p>
<p>There’s another small detail involved here: this means that if you use <code>if</code>
in this way, both arms of the <code>if</code> must be the same type. This doesn’t work:</p>
<pre><code class="language-rust,ignore">fn main() {
let condition = true;
let number = if condition {
5
} else {
&quot;six&quot;
};
println!(&quot;The value of number is: {}&quot;, number);
}
</code></pre>
<p>If we try to run this, we’ll get an error:</p>
<pre><code class="language-bash"> Compiling branches v0.1.0 (file:///projects/branches)
src/main.rs:4:18: 8:6 error: if and else have incompatible types:
expected `_`,
found `&amp;‘static str`
(expected integral variable,
found &amp;-ptr) [E0308]
src/main.rs:4 let number = if condition {
src/main.rs:5 5
src/main.rs:6 } else {
src/main.rs:7 &quot;six&quot;
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`.
</code></pre>
<p><code>if</code> and <code>else</code> have incompatible types. This can’t work.</p>
<h1>Loops</h1>
<p>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’.</p>
<p>To try out loops, let’s make a new project. Navigate to your projects folder
and use Cargo to make a new one:</p>
<pre><code class="language-bash">$ cargo new --bin loops
$ cd loops
</code></pre>
<p>There are three kinds of loops in Rust: <code>loop</code>, <code>while</code>, and <code>for</code>. Let’s dig
in.</p>
<h2><code>loop</code></h2>
<p>The <code>loop</code> keyword is very straightforward: it executes a block of code over
and over and over and over and over and over forever. Change your <code>src/main.rs</code>
file to look like this:</p>
<pre><code class="language-rust,ignore">fn main() {
loop {
println!(&quot;again!&quot;);
}
}
</code></pre>
<p>If we run this program, we’ll see ‘<code>again!</code>’ 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:</p>
<pre><code class="language-bash">$ cargo run
Compiling loops v0.1.0 (file:///projects/loops)
Running `target/debug/loops`
again!
again!
again!
again!
^Cagain!
</code></pre>
<p>That <code>^C</code> there is where I hit control-c.</p>
<p>That’s a lot of trouble though! Luckily, there’s a way to break an infinite <code>loop</code>.</p>
<h3>Breaking out of a loop</h3>
<p>The <code>break</code> keyword will allow us to quit looping. Try this version out:</p>
<pre><code class="language-rust">fn main() {
loop {
println!(&quot;once!&quot;);
break;
}
}
</code></pre>
<p>If you run this program with <code>cargo run</code>, you’ll see that it only executes one
time:</p>
<pre><code class="language-bash">$ cargo run
Compiling loops v0.1.0 (file:///projects/loops)
Running `target/debug/loops`
once!
</code></pre>
<p>When a Rust program hits a <code>break</code> statement, it will exit the current loop.</p>
<h2><code>while</code></h2>
<p>What if we took <code>loop</code>, <code>break</code>, and <code>if</code>, and put them together? Something
like this:</p>
<pre><code class="language-rust">fn main() {
let mut number = 3;
loop {
if number != 0 {
println!(&quot;{}!&quot;, number);
number = number - 1;
} else {
break;
}
}
println!(&quot;LIFTOFF!!!&quot;);
}
</code></pre>
<p>If we run this, we’ll get some output:</p>
<pre><code class="language-bash"> Compiling loops v0.1.0 (file:///projects/loops)
Running `target/debug/loops`
3!
2!
1!
LIFTOFF!!!
</code></pre>
<p>The core of this example is in the combination of these three constructs:</p>
<pre><code class="language-rust,ignore"> loop {
if number != 0 {
// do stuff
} else {
break;
}
</code></pre>
<p>We want to <code>loop</code>, but only while some sort of condition is true. As soon as it
isn't, we want to <code>break</code> out of the loop.</p>
<p>This pattern is so common that we have a language construct for it: <code>while</code>.
Here's the same example, but using <code>while</code> instead:</p>
<pre><code class="language-rust">fn main() {
let mut number = 3;
while number != 0 {
println!(&quot;{}!&quot;, number);
number = number - 1;
}
println!(&quot;LIFTOFF!!!&quot;);
}
</code></pre>
<p>This lets us get rid of a lot of nesting, and is more clear: while a condition holds,
run this code.</p>
<h2><code>for</code></h2>
<p>We can use this <code>while</code> construct to loop over the elements of a collection, like an
array:</p>
<pre><code class="language-rust">fn main() {
let a = [1, 2, 3, 4, 5];
let mut index = 0;
while index &lt; 5 {
println!(&quot;the value is is: {}&quot;, a[index]);
index = index + 1;
}
}
</code></pre>
<p>Running this will print out every element of the array:</p>
<pre><code class="language-bash">$ 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
</code></pre>
<p>Here, we're counting up instead of down: we start at zero, then loop until we
hit the final index of our array.</p>
<p>This approach is error-prone, though. If we get the index length incorrect, we
will end up causing a <code>panic!</code>. This is also slow, as the compiler needs to do
that check on every element on every iteration through the loop.</p>
<p>Instead, we can use our last kind of loop: the <code>for</code> loop. It looks like this:</p>
<pre><code class="language-rust">fn main() {
let a = [1, 2, 3, 4, 5];
let mut index = 0;
for element in a.iter() {
println!(&quot;the value is: {}&quot;, element);
}
}
</code></pre>
<p>** NOTE: see <a href="https://github.com/rust-lang/rust/issues/25725#issuecomment-166365658">https://github.com/rust-lang/rust/issues/25725#issuecomment-166365658</a>, we may want to change this **</p>
<p>If we run this, we'll see the same output as the previous example.</p>
<p>** I'm going to leave it at this for now until we decide how we want to do it**</p>
<h1>Understanding Ownership</h1>
<p>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.</p>
<h1>Ownership</h1>
<p>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.</p>
<p>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.</p>
<p>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!</p>
<p>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.</p>
<h2>Variable binding scope</h2>
<p>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 <code>fn main() {</code> stuff in examples, so
if you’re following along, you will have to put them inside of a <code>main()</code>
function. This lets our examples be a bit more concise, letting us focus on the
actual details, rather than boilerplate.</p>
<p>Anyway, here it is:</p>
<pre><code class="language-rust">let s = &quot;hello&quot;;
</code></pre>
<p>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 <em>scope</em>. That is:</p>
<pre><code class="language-rust">{ // s is not valid here, it’s not yet in scope
let s = &quot;hello&quot;; // s is valid from this point forward
// do stuff with s
} // this scope is now over, and s is no longer valid
</code></pre>
<p>In other words, there are two important points in time here:</p>
<ul>
<li>When <code>s</code> comes ‘into scope’, it is valid.</li>
<li>It remains so until it ‘goes out of scope’.</li>
</ul>
<p>At this point, things are similar to other programming languages. Let’s build
on top of this understanding by introducing a new type: <code>String</code>.</p>
<h2>Strings</h2>
<p>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?</p>
<p>For this, Rust has a second string type, <code>String</code>. You can create a <code>String</code> from
a string literal using the <code>from</code> function:</p>
<pre><code class="language-rust">let s = String::from(&quot;hello&quot;);
</code></pre>
<p>We haven’t seen the double colon (<code>::</code>) syntax yet. It is a kind of scope
operator, allowing us to namespace this particular <code>from()</code> function under the
<code>String</code> type itself, rather than using some sort of name like <code>string_from()</code>.
We’ll discuss this syntax more in the “Method Syntax” and “Modules” chapters.</p>
<p>This kind of string can be mutated:</p>
<pre><code class="language-rust">let mut s = String::from(&quot;hello&quot;);
s.push_str(&quot;, world!&quot;);
</code></pre>
<h2>Memory and allocation</h2>
<p>So, what’s the difference here? Why can <code>String</code> be mutated, but literals
cannot? The difference comes down to how these two types deal with memory.</p>
<p>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!</p>
<p>With <code>String</code>, to support a mutable, growable string, we need to allocate an
unknown amount of memory to hold the contents. This means two things:</p>
<ol>
<li>The memory must be requested from the operating system at runtime.</li>
<li>We need a way of giving this memory back to the operating system when we’re
done with our <code>String</code>.</li>
</ol>
<p>That first part is done by us: when we call <code>String::from()</code>, its
implementation requests the memory it needs. This is pretty much universal in
programming languages.</p>
<p>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
<code>allocate()</code> with exactly one <code>free()</code>.</p>
<p>Rust takes a different path. Remember our example? Here’s a version with
<code>String</code>:</p>
<pre><code class="language-rust">{
let s = String::from(&quot;hello&quot;); // s is valid from this point forward
// do stuff with s
} // this scope is now over, and s is no longer valid
</code></pre>
<p>We have a natural point at which we can return the memory our <code>String</code> 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 <code>drop()</code>, and it
is where the author of <code>String</code> can put the code to return the memory.</p>
<blockquote>
<p>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 <em>roughly</em> similar in Rust, but not identical.</p>
</blockquote>
<p>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.</p>
<h2>Move</h2>
<p>What would you expect this code to do?</p>
<pre><code class="language-rust">let x = 5;
let y = x;
</code></pre>
<p>You might say “Make a copy of <code>5</code>.” That’d be correct! We now have two
bindings, <code>x</code> and <code>y</code>, and both equal <code>5</code>.</p>
<p>Now let’s look at <code>String</code>. What would you expect this code to do?</p>
<pre><code class="language-rust">let s1 = String::from(&quot;hello&quot;);
let s2 = s1;
</code></pre>
<p>You might say “copy the <code>String</code>!” This is both correct and incorrect at the
same time. It does a <em>shallow</em> copy of the <code>String</code>. What’s that mean? Well,
let’s take a look at what <code>String</code> looks like under the covers:</p>
<p><img alt="string" src="img/foo1.png" class="center" style="width: 50%;" /></p>
<p>A <code>String</code> 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 <code>String</code> is currently using. The capacity is the total amount of memory the
<code>String</code> 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.</p>
<blockquote>
<p>We’ve talked about two kinds of composite types: arrays and tuples. <code>String</code>
is a third type: a <code>struct</code>, which we will cover the details of in the next
chapter of the book. For now, thinking about <code>String</code> as a tuple is close
enough.</p>
</blockquote>
<p>When we assign <code>s1</code> to <code>s2</code>, the <code>String</code> 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:</p>
<p><img alt="s1 and s2" src="img/foo2.png" class="center" style="width: 50%;" /></p>
<p><em>Not</em> this:</p>
<p><img alt="s1 and s2 to two places" src="img/foo4.png" class="center" style="width: 50%;" /></p>
<p>When moving, Rust makes a copy of the data structure itself, the contents of
<code>s1</code> are copied, but if <code>s1</code> contains a reference, like it does in this case,
Rust will not copy the things that those references refer to.</p>
<p>There’s a problem here! Both <code>data</code> pointers are pointing to the same place.
Why is this a problem? Well, when <code>s2</code> goes out of scope, it will free the
memory that <code>data</code> points to. And then <code>s1</code> goes out of scope, and it will
<em>also</em> try to free the memory that <code>data</code> points to! That’s bad.</p>
<p>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 <code>String</code> contained a novel? Also,
it only works for memory. What if, instead of a <code>String</code>, we had a
<code>TcpConnection</code>? 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 <code>drop()</code>, and write code
fix things up. That would work, but now, an <code>=</code> can run arbitrary code. That’s
also not good, and it doesn’t solve our efficiency concerns either.</p>
<p>Let’s take a step back: the root of the problem is that <code>s1</code> and <code>s2</code> 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 <code>s1</code> 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 <code>s1</code>
after <code>s2</code> is created:</p>
<pre><code class="language-rust,ignore">let s1 = String::from(&quot;hello&quot;);
let s2 = s1;
println!(&quot;{}&quot;, s1);
</code></pre>
<p>You’ll get an error like this:</p>
<pre><code class="language-text">5:22 error: use of moved value: `s1` [E0382]
println!(&quot;{}&quot;, s1);
^~
5:24 note: in this expansion of println! (defined in &lt;std macros&gt;)
3:11 note: `s1` moved here because it has type `collections::string::String`, which is moved by default
let s2 = s1;
^~
</code></pre>
<p>We say that <code>s1</code> was <em>moved</em> into <code>s2</code>. When a value moves, its data is copied,
but the original variable binding is no longer usable. That solves our problem:</p>
<p><img alt="s1 and s2 to the same place" src="img/foo3.png" class="center" style="width: 50%;" /></p>
<p>With only <code>s2</code> valid, when it goes out of scope, it will free the memory, and we’re done!</p>
<h2>Ownership Rules</h2>
<p>This leads us to the Ownership Rules:</p>
<blockquote>
<ol>
<li>Each value in Rust has a variable binding that’s called it’s ‘owner’.</li>
<li>There can only be one owner at a time.</li>
<li>When the owner goes out of scope, the value will be <code>drop()</code>ped.</li>
</ol>
</blockquote>
<p>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.</p>
<h2>Clone</h2>
<p>But what if we <em>do</em> want to deeply copy the <code>String</code>’s data, and not just the
<code>String</code> itself? There’s a common method for that: <code>clone()</code>. Here’s an example
of <code>clone()</code> in action:</p>
<pre><code class="language-rust">let s1 = String::from(&quot;hello&quot;);
let s2 = s1.clone();
println!(&quot;{}&quot;, s1);
</code></pre>
<p>This will work just fine. Remember our diagram from before? In this case,
it <em>is</em> doing this:</p>
<p><img alt="s1 and s2 to two places" src="img/foo4.png" class="center" style="width: 50%;" /></p>
<p>When you see a call to <code>clone()</code>, 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.</p>
<h2>Copy</h2>
<p>There’s one last wrinkle that we haven’t talked about yet. This code works:</p>
<pre><code class="language-rust">let x = 5;
let y = x;
println!(&quot;{}&quot;, x);
</code></pre>
<p>But why? We don’t have a call to <code>clone()</code>. Why didn’t <code>x</code> get moved into <code>y</code>?</p>
<p>For types that do not have any kind of complex storage requirements, like
integers, typing <code>clone()</code> is busy work. There’s no reason we would ever want
to prevent <code>x</code> 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 <code>clone()</code> wouldn’t do anything differently from the
usual shallow copying.</p>
<p>Rust has a special annotation that you can place on types, called <code>Copy</code>. If
a type is <code>Copy</code>, an older binding is still usable after assignment. Integers
are an example of such a type; most of the primitive types are <code>Copy</code>.</p>
<p>While we haven’t talked about how to mark a type as <code>Copy</code> yet, you might ask
yourself “what happens if we made <code>String</code> <code>Copy</code>?” The answer is, you cannot.
Remember <code>drop()</code>? Rust will not let you make something <code>Copy</code> if it has
implemented <code>drop()</code>. If you need to do something special when the value goes
out of scope, being <code>Copy</code> will be an error.</p>
<p>So what types are <code>Copy</code>? 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 <code>Copy</code>.
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.</p>
<p>Here’s some types that you’ve seen so far that are <code>Copy</code>:</p>
<ul>
<li>All of the integer types, like <code>u32</code>.</li>
<li>The booleans, <code>true</code> and <code>false</code>.</li>
<li>All of the floating point types, like <code>f64</code>.</li>
<li>Tuples, but only if they contain types which are also <code>Copy</code>. <code>(i32, i32)</code>
is <code>Copy</code>, but <code>(i32, String)</code> is not!</li>
</ul>
<h2>Ownership and functions</h2>
<p>Passing a value to a function has similar semantics as assigning it:</p>
<pre><code class="language-rust">fn main() {
let s = String::from(&quot;hello&quot;);
takes_ownership(s);
let x = 5;
makes_copy(x);
}
fn takes_ownership(some_string: String) {
println!(&quot;{}&quot;, some_string);
}
fn makes_copy(some_integer: i32) {
println!(&quot;{}&quot;, some_integer);
}
</code></pre>
<p>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:</p>
<pre><code class="language-rust">fn main() {
let s = String::from(&quot;hello&quot;); // 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!(&quot;{}&quot;, 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!(&quot;{}&quot;, some_integer);
} // Here, some_integer goes out of scope. Nothing special happens.
</code></pre>
<p>Remember: If we tried to use <code>s</code> after the call to <code>takes_ownership()</code>, Rust
would throw a compile-time error! These static checks protect us from mistakes.</p>
<p>Returning values can also transfer ownership:</p>
<pre><code class="language-rust">fn main() {
let s1 = gives_ownership();
let s2 = String::from(&quot;hello&quot;);
let s3 = takes_and_gives_back(s2);
}
fn gives_ownership() -&gt; String {
let some_string = String::from(&quot;hello&quot;);
some_string
}
fn takes_and_gives_back(a_string: String) -&gt; String {
a_string
}
</code></pre>
<p>With simililar annotations:</p>
<pre><code class="language-rust">fn main() {
let s1 = gives_ownership(); // gives_ownership moves its return
// value into s1.
let s2 = String::from(&quot;hello&quot;); // 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() -&gt; String { // gives_ownership will move its
// return value into the function
// that calls it.
let some_string = String::from(&quot;hello&quot;); // 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) -&gt; String { // a_string comes into scope
a_string // a_string is returned, and moves out to the calling function
}
</code></pre>
<p>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 <code>drop()</code>.</p>
<p>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:</p>
<pre><code class="language-rust">fn main() {
let s1 = String::from(&quot;hello&quot;);
let (s2, len) = calculate_length(s1);
println!(&quot;The length of '{}' is {}.&quot;, s2, len);
}
fn calculate_length(s: String) -&gt; (String, usize) {
let length = s.len(); // len() returns the length of a String.
(s, length)
}
</code></pre>
<p>This is too much ceremony: we have to use a tuple to give back the <code>String</code> as
well as the length. It’s a lot of work for a pattern that should be common.</p>
<p>Luckily for us, Rust has such a feature, and it’s what the next section is about.</p>
<h1>References and Borrowing</h1>
<p>At the end of the last section, we had some example Rust that wasn’t very
good. Here it is again:</p>
<pre><code class="language-rust">fn main() {
let s1 = String::from(&quot;hello&quot;);
let (s2, len) = calculate_length(s1);
println!(&quot;The length of '{}' is {}.&quot;, s2, len);
}
fn calculate_length(s: String) -&gt; (String, usize) {
let length = s.len(); // len() returns the length of a String.
(s, length)
}
</code></pre>
<p>The issue here is that we have to return the <code>String</code> back to the calling
function so that it could still use it.</p>
<p>There is a better way. It looks like this:</p>
<pre><code class="language-rust">fn main() {
let s1 = String::from(&quot;hello&quot;);
let len = calculate_length(&amp;s1);
println!(&quot;The length of '{}' is {}.&quot;, s1, len);
}
fn calculate_length(s: &amp;String) -&gt; usize {
let length = s.len();
length
}
</code></pre>
<p>First, you’ll notice all of the tuple stuff is gone. Next, that we pass <code>&amp;s1</code>
into <code>calculate_lengths()</code>. And in its definition, we take <code>&amp;String</code> rather
than <code>String</code>.</p>
<p>These <code>&amp;s</code> are called ‘references’, and they allow you to refer to some value
without taking ownership of it. Here’s a diagram:</p>
<p>DIAGRAM GOES HERE of a &amp;String pointing at a String, with (ptr, len, capacity)</p>
<p>Let’s take a closer look at the function call here:</p>
<pre><code class="language-rust"># fn calculate_length(s: &amp;String) -&gt; usize {
# let length = s.len();
#
# length
# }
let s1 = String::from(&quot;hello&quot;);
let len = calculate_length(&amp;s1);
</code></pre>
<p>The <code>&amp;s1</code> syntax lets us create a reference from <code>s1</code>. This reference <em>refers</em>
to the value of <code>s1</code>, 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.</p>
<p>Likewise, the signature of the function uses <code>&amp;</code> to indicate that it takes
a reference as an argument:</p>
<p>Let’s add some explanatory annotations:</p>
<pre><code class="language-rust">fn calculate_length(s: &amp;String) -&gt; 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.
</code></pre>
<p>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.</p>
<p>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.</p>
<p>Speaking of which, what if you try to modify something you borrow from me? Try
this code out. Spoiler alert: it doesn’t work:</p>
<pre><code class="language-rust,ignore">fn main() {
let s = String::from(&quot;hello&quot;);
change(&amp;s);
}
fn change(some_string: &amp;String) {
some_string.push_str(&quot;, world&quot;); // push_str() appends a literal to a String
}
</code></pre>
<p>Here’s the error:</p>
<pre><code class="language-text">8:16 error: cannot borrow immutable borrowed content `*some_string` as mutable
some_string.push_str(&quot;, world&quot;); // push_str() appends a literal to a String
^~~~~~~~~~~
</code></pre>
<p>Just like bindings are immutable by default, so are references. We’re not allowed
to modify something we have a reference to.</p>
<h2>Mutable references</h2>
<p>We can fix this bug! Just a small tweak:</p>
<pre><code class="language-rust">fn main() {
let mut s = String::from(&quot;hello&quot;);
change(&amp;mut s);
}
fn change(some_string: &amp;mut String) {
some_string.push_str(&quot;, world&quot;); // push_str() appends a literal to a String
}
</code></pre>
<p>First, we had to change <code>s</code> to be <code>mut</code>. Then, we had to create a mutable reference
with <code>&amp;mut s</code> and accept a mutable reference with <code>some_string: &amp;mut String</code>.</p>
<p>Mutable references have one big restriction, though. This code fails:</p>
<pre><code class="language-rust,ignore">let mut s = String::from(&quot;hello&quot;);
let r1 = &amp;mut s;
let r2 = &amp;mut s;
</code></pre>
<p>Here’s the error:</p>
<pre><code class="language-text">5:20 error: cannot borrow `s` as mutable more than once at a time [E0499]
let r2 = &amp;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 = &amp;mut s;
^
7:2 note: previous borrow ends here
fn main() {
}
^
</code></pre>
<p>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.</p>
<p>As always, we can use <code>{}</code>s to create a new scope, allowing for multiple mutable
references. Just not <em>simultaneous</em> ones:</p>
<pre><code class="language-rust">let mut s = String::from(&quot;hello&quot;);
{
let r1 = &amp;mut s;
} // r1 goes out of scope here, so we can make a new reference with no problems.
let r2 = &amp;mut s;
</code></pre>
<p>There is a simlar rule for combining the two kinds of references. This code errors:</p>
<pre><code class="language-rust,ignore">let mut s = String::from(&quot;hello&quot;);
let r1 = &amp;s; // no problem
let r2 = &amp;s; // no problem
let r3 = &amp;mut s; // BIG PROBLEM
</code></pre>
<p>Here’s the error:</p>
<pre><code class="language-text">19: 6:20 error: cannot borrow `s` as mutable because it is also borrowed as
immutable [E0502]
let r3 = &amp;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 = &amp;s; // no problem
^
8:2 note: previous borrow ends here
fn main() {
}
^
</code></pre>
<p>Whew! We <em>also</em> 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.</p>
<h2>Dangling references</h2>
<p>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.</p>
<p>Let’s try to create a dangling reference:</p>
<pre><code class="language-rust,ignore">fn main() {
let reference_to_nothing = dangle();
}
fn dangle() -&gt; &amp;String {
let s = String::from(&quot;hello&quot;);
&amp;s
}
</code></pre>
<p>Here’s the error:</p>
<pre><code class="language-text">error: missing lifetime specifier [E0106]
fn dangle() -&gt; &amp;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
</code></pre>
<p>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:</p>
<pre><code class="language-text">this function’s return type contains a borrowed value, but there is no value
for it to be borrowed from
</code></pre>
<p>Let’s examine exactly what happens with <code>dangle()</code>:</p>
<pre><code class="language-rust,ignore">fn dangle() -&gt; &amp;String { // dangle returns a reference to a String
let s = String::from(&quot;hello&quot;); // s is a new String
&amp;s // we return a reference to the String, s
} // Here, s goes out of scope, and is dropped. Its memory goes away.
// Danger!
</code></pre>
<p>Because <code>s</code> is created inside of <code>dangle()</code>, when the code of <code>dangle()</code> 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 <code>String</code>! That’s
no good. Rust won’t let us do this.</p>
<p>The correct code here is to return the <code>String</code> directly:</p>
<pre><code class="language-rust">fn no_dangle() -&gt; String {
let s = String::from(&quot;hello&quot;);
s
}
</code></pre>
<p>This works, no problem. Ownership is moved out, nothing is deallocated.</p>
<h2>The Rules of References</h2>
<p>Here’s a recap of what we’ve talked about:</p>
<ol>
<li>At any given time, you may have <em>either</em>, but not both of:
<ol>
<li>One mutable reference.</li>
<li>Any number of immutable references .</li>
</ol>
</li>
<li>References must always be valid.</li>
</ol>
<p>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.</p>
<h2>More Examples</h2>
<p>COMING SOON</p>
<h1>Slices</h1>
<p>So far, we’ve talked about types that have ownership, like <code>String</code>, and ones
that don’t, like <code>&amp;String</code>. 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.</p>
<p>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.</p>
<p>Let’s think about the signature of this function:</p>
<pre><code class="language-rust,ignore">fn first_word(s: &amp;String) -&gt; ?
</code></pre>
<p>This function, <code>first_word</code>, takes a <code>&amp;String</code> 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 <em>part</em> of a string. We could return the index of the end of
the word, though. Let’s try that:</p>
<pre><code class="language-rust">fn first_word(s: &amp;String) -&gt; usize {
let bytes = s.as_bytes();
for (i, &amp;byte) in bytes.iter().enumerate() {
if byte == 32 {
return i;
}
}
s.len()
}
</code></pre>
<p>Let’s break that down a bit:</p>
<pre><code class="language-rust">fn first_word(s: &amp;String) -&gt; 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 &amp;byte for
// the byte itself.
for (i, &amp;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()
}
</code></pre>
<p>This works, but there’s a problem. We’re returning a <code>usize</code> on its own, but
it’s only a meaningful number in the context of the <code>&amp;String</code> itself. In other
words, because it’s a separate value from the <code>String</code>, there’s no guarantee
that it will still be valid in the future. Consider this:</p>
<pre><code class="language-rust"># fn first_word(s: &amp;String) -&gt; usize {
# let bytes = s.as_bytes();
#
# for (i, &amp;byte) in bytes.iter().enumerate() {
# if byte == 32 {
# return i;
# }
# }
#
# s.len()
# }
fn main() {
let mut s = String::from(&quot;hello world&quot;);
let word = first_word(&amp;s);
s.clear(); // This empties the String, making it equal to &quot;&quot;.
// word is now totally invalid! There’s no more word here.
}
</code></pre>
<p>This is bad! It’s even worse if we wanted to write a <code>second_word()</code>
function. Its signature would have to look like this:</p>
<pre><code class="language-rust,ignore">fn second_word(s: &amp;String) -&gt; (usize, usize) {
</code></pre>
<p>Now we’re tracking both a start <em>and</em> 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.</p>
<p>Luckily, Rust has a solution to this probem: string slices.</p>
<h1>String slices</h1>
<p>A string slice looks like this:</p>
<pre><code class="language-rust">let s = String::from(&quot;hello world&quot;);
let hello = &amp;s[0..5];
let world = &amp;s[6..11];
</code></pre>
<p>This looks just like taking a reference to the whole <code>String</code>, but with the
extra <code>[0..5]</code> bit. Instead of being a reference to the entire <code>String</code>,
it’s a reference to an internal position in the <code>String</code>, but it also keeps
track of the number of elements that it refers to as well. In other words,
it looks like this:</p>
<p>DIAGRAM GOES HERE of s, hello, and world</p>
<p>Note that the internal position is specified through byte-offsets, not
characters. The offset to the first byte of a <code>String</code> is 0 and the
trailing number should point to the first byte that is <em>not</em> included
in the slice.</p>
<p>With Rust’s <code>..</code> syntax, if you want to start at zero, you can drop the zero.
In other words, these are equal:</p>
<pre><code class="language-rust">let s = String::from(&quot;hello&quot;);
let slice = &amp;s[0..2];
let slice = &amp;s[..2];
</code></pre>
<p>By the same token, if your slice should include the last byte of the
<code>String</code>, you can drop the trailing number. In other words, these are
equal:</p>
<pre><code class="language-rust">let s = String::from(&quot;hello&quot;);
let len = s.len();
let slice = &amp;s[0..len];
let slice = &amp;s[0..];
</code></pre>
<p>With this in mind, let’s re-write <code>first_word()</code> to return a slice:</p>
<pre><code class="language-rust">fn first_word(s: &amp;String) -&gt; &amp;str {
let bytes = s.as_bytes();
for (i, &amp;byte) in bytes.iter().enumerate() {
if byte == 32 {
return &amp;s[0..i];
}
}
&amp;s[..]
}
</code></pre>
<p>Now, we have a single value, the <code>&amp;str</code>. 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 <code>second_word()</code>:</p>
<pre><code class="language-rust,ignore">fn second_word(s: &amp;String) -&gt; &amp;str {
</code></pre>
<p>Same deal. We now have a straightforward API, that’s much harder to mess up.</p>
<p>But what about our error condition from before? Slices also fix that. Using
the slice version of <code>first_word()</code> will throw an error:</p>
<pre><code class="language-rust,ignore"># fn first_word(s: &amp;String) -&gt; &amp;str {
# let bytes = s.as_bytes();
#
# for (i, &amp;byte) in bytes.iter().enumerate() {
# if byte == 32 {
# return &amp;s[0..i];
# }
# }
#
# &amp;s[..]
# }
fn main() {
let mut s = String::from(&quot;hello world&quot;);
let word = first_word(&amp;s);
s.clear(); // Error!
}
</code></pre>
<p>Here’s the error:</p>
<pre><code class="language-text">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(&amp;s);
^
18:2 note: previous borrow ends here
fn main() {
}
^
</code></pre>
<p>Remember the borrowing rules? If we have an immutable reference to something,
we cannot also take a mutable reference. Since <code>clear()</code> needs to truncate the
<code>String</code>, 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!</p>
<h3>String literals are slices</h3>
<p>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.</p>
<pre><code class="language-rust">let s = &quot;Hello, world!&quot;;
</code></pre>
<p>The type of <code>s</code> here is <code>&amp;str</code>: It’s a slice, pointing to that specific point
of the binary. This is also why string literals are immutable; <code>&amp;str</code> is an
immutable reference.</p>
<h2>String slices as arguments</h2>
<p>Knowing that you can take slices of both literals and <code>String</code>s leads us to
one more improvement on <code>first_word()</code>, and that’s its signature:</p>
<pre><code class="language-rust,ignore">fn first_word(s: &amp;String) -&gt; &amp;str {
</code></pre>
<p>A more experienced Rustacean would write this one instead:</p>
<pre><code class="language-rust,ignore">fn first_word(s: &amp;str) -&gt; &amp;str {
</code></pre>
<p>Why is this? Well, we aren’t trying to modify <code>s</code> at all. And we can take
a string slice that’s the full length of a <code>String</code>, so we haven’t lost
the ability to talk about full <code>String</code>s. And additionally, we can take
string slices of string literals too, so this function is more useful, but
with no loss of functionality:</p>
<pre><code class="language-rust"># fn first_word(s: &amp;str) -&gt; &amp;str {
# let bytes = s.as_bytes();
#
# for (i, &amp;byte) in bytes.iter().enumerate() {
# if byte == 32 {
# return &amp;s[0..i];
# }
# }
#
# &amp;s[..]
# }
fn main() {
let s = String::from(&quot;hello world&quot;);
let word = first_word(&amp;s[..]);
let s = &quot;hello world&quot;;
let word = first_word(&amp;s[..]);
let word = first_word(s); // since literals are &amp;strs, this works too!
}
</code></pre>
<h1>Other slices</h1>
<p>String slices, as you might imagine, are specific to strings. But there’s a more
general slice type, too. Consider arrays:</p>
<pre><code class="language-rust">let a = [1, 2, 3, 4, 5];
</code></pre>
<p>Just like we may want to refer to a part of a string, we may want to refer to
part of an array:</p>
<pre><code class="language-rust">let a = [1, 2, 3, 4, 5];
let slice = &amp;a[1..3];
</code></pre>
<p>This slice has the type <code>&amp;[i32]</code>. 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.</p>
<h1>Structs</h1>
<p>So far, all of the data types we’ve seen allow us to have a single value
at a time. <code>struct</code>s give us the ability to package up multiple values and
keep them in one related structure.</p>
<p>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 <code>struct</code>s instead.</p>
<p>Let’s make a new project with Cargo:</p>
<pre><code class="language-bash">$ cargo new --bin points
$ cd points
</code></pre>
<p>Here’s a short program which calculates the distance between two points. Put
it into your <code>src/main.rs</code>:</p>
<pre><code class="language-rust">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!(&quot;Point 1: ({}, {})&quot;, x1, y1);
println!(&quot;Point 2: ({}, {})&quot;, x2, y2);
println!(&quot;Distance: {}&quot;, answer);
}
fn distance(x1: f64, y1: f64, x2: f64, y2: f64) -&gt; f64 {
let x_squared = f64::powi(x2 - x1, 2);
let y_squared = f64::powi(y2 - y1, 2);
f64::sqrt(x_squared + y_squared)
}
</code></pre>
<p>Let's try running this program with <code>cargo run</code>:</p>
<pre><code class="language-bash">$ cargo run
Compiling points v0.1.0 (file:///projects/points)
Running `target/debug/points`
Point 1: (0, 5)
Point 2: (12, 0)
Distance: 13
</code></pre>
<p>Let's take a quick look at <code>distance()</code> before we move forward:</p>
<pre><code class="language-rust">fn distance(x1: f64, y1: f64, x2: f64, y2: f64) -&gt; f64 {
let x_squared = f64::powi(x2 - x1, 2);
let y_squared = f64::powi(y2 - y1, 2);
f64::sqrt(x_squared + y_squared)
}
</code></pre>
<p>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.</p>
<pre><code class="language-rust,ignore">f64::powi(2.0, 3)
</code></pre>
<p>The double colon (<code>::</code>) here is a namespace operator. We haven’t talked about
modules yet, but you can think of the <code>powi()</code> function as being scoped inside
of another name. In this case, the name is <code>f64</code>, the same as the type. The
<code>powi()</code> 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, <code>sqrt()</code> is a function under the
<code>f64</code> module, which takes the square root of its argument.</p>
<h2>Why <code>struct</code>s?</h2>
<p>Our little program is okay, but we can do better. The key is in the signature
of <code>distance()</code>:</p>
<pre><code class="language-rust,ignore">fn distance(x1: f64, y1: f64, x2: f64, y2: f64) -&gt; f64 {
</code></pre>
<p>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 <code>(x1, y1)</code> and <code>(x2, y2)</code>
together.</p>
<p>We’ve already discussed one way to do that: tuples. Here’s a version of our program
which uses tuples:</p>
<pre><code class="language-rust">fn main() {
let p1 = (0.0, 5.0);
let p2 = (12.0, 0.0);
let answer = distance(p1, p2);
println!(&quot;Point 1: {:?}&quot;, p1);
println!(&quot;Point 2: {:?}&quot;, p2);
println!(&quot;Distance: {}&quot;, answer);
}
fn distance(p1: (f64, f64), p2: (f64, f64)) -&gt; 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)
}
</code></pre>
<p>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:</p>
<pre><code class="language-rust,ignore">p2.0 - p1.0
p2.1 - p1.1
</code></pre>
<p>When writing this example, your authors almost got it wrong themselves! Distance
is all about <code>x</code> and <code>y</code> points, but now it’s all about <code>0</code> and <code>1</code>. This isn’t
great.</p>
<p>Enter <code>struct</code>s. We can transform our tuples into something with a name:</p>
<pre><code class="language-rust,ignore">let p1 = (0.0, 5.0);
struct Point {
x: f64,
y: f64,
}
let p1 = Point { x: 0.0, y: 5.0 };
</code></pre>
<p>Here’s what declaring a <code>struct</code> looks like:</p>
<pre><code class="language-text">struct NAME {
NAME: TYPE,
}
</code></pre>
<p>The <code>NAME: TYPE</code> 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 <code>{}</code>s:</p>
<pre><code class="language-rust">struct Foo;
</code></pre>
<p><code>struct</code>s with no fields are called ‘unit structs’, and are used in certain
advanced situations. We will just ignore them for now.</p>
<p>You can access the field of a struct in the same way you access an element of
a tuple, except you use its name:</p>
<pre><code class="language-rust,ignore">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;
</code></pre>
<p>Let’s convert our program to use our <code>Point</code> <code>struct</code>. Here’s what it looks
like now:</p>
<pre><code class="language-rust">#[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!(&quot;Point 1: {:?}&quot;, p1);
println!(&quot;Point 2: {:?}&quot;, p2);
println!(&quot;Distance: {}&quot;, answer);
}
fn distance(p1: Point, p2: Point) -&gt; 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)
}
</code></pre>
<p>Our function signature for <code>distance()</code> now says exactly what we mean: it
calculates the distance between two <code>Point</code>s. And rather than <code>0</code> and <code>1</code>,
we’ve got back our <code>x</code> and <code>y</code>. This is a win for clarity.</p>
<p>There’s one other thing that’s a bit strange here, this annotation on our
<code>struct</code> declaration:</p>
<pre><code class="language-rust,ignore">#[derive(Debug,Copy,Clone)]
struct Point {
</code></pre>
<p>We haven’t yet talked about traits, but we did talk about <code>Debug</code> when we
discussed arrays. This <code>derive</code> attribute allows us to tweak the behavior of
our <code>Point</code>. In this case, we are opting into copy semantics, and everything
that implements <code>Copy</code> must implement <code>Clone</code>.</p>
</div>
<!-- Mobile navigation buttons -->
</div>
</div>
<!-- Local fallback for Font Awesome -->
<script>
if ($(".fa").css("font-family") !== "FontAwesome") {
$('<link rel="stylesheet" type="text/css" href="_FontAwesome/css/font-awesome.css">').prependTo('head');
}
</script>
<script src="highlight.js"></script>
<script src="book.js"></script>
</body>
</html>