Files
book/variable-bindings.html
T

579 lines
29 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="{% block description %}{% endblock %}">
<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'>
<!-- 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" class="active"><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><strong>4.2.</strong> References &amp; Borrowing</li><li><strong>4.3.</strong> Memory Layout</li><li><strong>4.4.</strong> Slices</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>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>
</div>
<!-- Mobile navigation buttons -->
<a href="up-and-running.html" class="mobile-nav-chapters previous">
<i class="fa fa-angle-left"></i>
</a>
<a href="functions.html" class="mobile-nav-chapters next">
<i class="fa fa-angle-right"></i>
</a>
</div>
<a href="up-and-running.html" class="nav-chapters previous" title="You can navigate through the chapters using the arrow keys">
<i class="fa fa-angle-left"></i>
</a>
<a href="functions.html" class="nav-chapters next" title="You can navigate through the chapters using the arrow keys">
<i class="fa fa-angle-right"></i>
</a>
</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>