mirror of
https://github.com/rust-lang/book.git
synced 2026-11-30 20:24:32 -06:00
565 lines
29 KiB
HTML
565 lines
29 KiB
HTML
<!DOCTYPE HTML>
|
||
<html lang="en">
|
||
<head>
|
||
<meta charset="UTF-8">
|
||
<title></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><a href="tutorial.html"><strong>2.</strong> Tutorial</a></li><li><a href="basics.html"><strong>3.</strong> The Basics</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="primitive-types.html"><strong>3.3.</strong> Primitive Types</a></li><li><a href="comments.html"><strong>3.4.</strong> Comments</a></li><li><a href="if.html"><strong>3.5.</strong> `if`</a></li><li><a href="loops.html"><strong>3.6.</strong> Loops</a></li></ul></li><li><a href="ownership-and-borrowing.html"><strong>4.</strong> Ownership & borrowing</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 & Borrowing</a></li><li><a href="lifetimes.html"><strong>4.3.</strong> Lifetimes</a></li></ul></li><li><a href="basic-data-types.html"><strong>5.</strong> Basic Data Types</a></li><li><ul class="section"><li><a href="structs.html"><strong>5.1.</strong> Structs</a></li><li><a href="enums.html"><strong>5.2.</strong> Enums</a></li></ul></li><li><a href="crates-and-modules.html"><strong>6.</strong> Crates & Modules</a></li><li><a href="error-handling.html"><strong>7.</strong> Error Handling</a></li><li><a href="basic-collections.html"><strong>8.</strong> Basic Collections</a></li><li><ul class="section"><li><a href="vectors.html"><strong>8.1.</strong> Vectors</a></li><li><a href="strings.html"><strong>8.2.</strong> Strings</a></li><li><a href="hashmap.html"><strong>8.3.</strong> `HashMap<K, V>`</a></li></ul></li><li><a href="traits.html"><strong>9.</strong> Traits</a></li><li><a href="closures.html"><strong>10.</strong> Closures</a></li><li><a href="iterators.html"><strong>11.</strong> Iterators</a></li><li><a href="io.html"><strong>12.</strong> I/O</a></li><li><ul class="section"><li><a href="read-and-write.html"><strong>12.1.</strong> `Read` & `Write`</a></li><li><a href="fs.html"><strong>12.2.</strong> `std::fs`</a></li><li><a href="path.html"><strong>12.3.</strong> `std::path`</a></li><li><a href="env.html"><strong>12.4.</strong> `std::env`</a></li></ul></li><li><a href="testing.html"><strong>13.</strong> Testing</a></li><li><a href="smart-pointers.html"><strong>14.</strong> Smart Pointers</a></li><li><ul class="section"><li><a href="deref.html"><strong>14.1.</strong> `Deref`</a></li><li><a href="deref-coercions.html"><strong>14.2.</strong> `Deref` coercions</a></li><li><a href="box.html"><strong>14.3.</strong> `Box<T>`</a></li><li><a href="rc.html"><strong>14.4.</strong> `Rc<T>`</a></li></ul></li><li><a href="concurrency.html"><strong>15.</strong> Concurrency</a></li><li><ul class="section"><li><a href="threads.html"><strong>15.1.</strong> Threads</a></li><li><a href="send-and-sync.html"><strong>15.2.</strong> `Send` & `Sync`</a></li><li><a href="arc.html"><strong>15.3.</strong> `Arc<T>`</a></li><li><a href="mutex.html"><strong>15.4.</strong> `Mutex<T>`</a></li><li><a href="channels.html"><strong>15.5.</strong> `Channels`</a></li></ul></li><li><a href="unsafe-rust.html"><strong>16.</strong> Unsafe Rust</a></li><li><ul class="section"><li><a href="raw-pointers.html"><strong>16.1.</strong> Raw Pointers</a></li><li><a href="transmute.html"><strong>16.2.</strong> transmute</a></li></ul></li><li><a href="ffi.html"><strong>17.</strong> FFI</a></li><li><ul class="section"><li><a href="conditional-compilation.html"><strong>17.1.</strong> Conditional Compilation</a></li><li><a href="bindings-to-c.html"><strong>17.2.</strong> Bindings to C</a></li><li><a href="using-rust-from-other-languages.html"><strong>17.3.</strong> Using Rust from Other Languages</a></li><li><a href="static.html"><strong>17.4.</strong> `static`</a></li></ul></li><li><a href="cargo.html"><strong>18.</strong> Cargo</a></li><li><ul class="section"><li><a href="cratesio.html"><strong>18.1.</strong> Crates.io</a></li></ul></li><li><a href="advanced-type-system-features.html"><strong>19.</strong> Advanced Type System Features</a></li><li><ul class="section"><li><a href="associated-types.html"><strong>19.1.</strong> Associated Types</a></li><li><a href="trait-objects.html"><strong>19.2.</strong> Trait Objects</a></li><li><a href="ufcs.html"><strong>19.3.</strong> UFCS</a></li><li><a href="coherence.html"><strong>19.4.</strong> Coherence</a></li></ul></li><li><a href="interior-mutability.html"><strong>20.</strong> Interior mutability</a></li><li><ul class="section"><li><a href="cell.html"><strong>20.1.</strong> `Cell<T>`</a></li><li><a href="refcell.html"><strong>20.2.</strong> `RefCell<T>`</a></li></ul></li><li><a href="macros.html"><strong>21.</strong> Macros</a></li><li><a href="nightly-rust.html"><strong>22.</strong> Nightly Rust</a></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"></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!("Hello, world!");
|
||
}
|
||
</code></pre>
|
||
<p>Let’s replace that program with this one:</p>
|
||
<pre><code class="language-rust">fn main() {
|
||
let x = 5;
|
||
|
||
println!("The value of x is: {}", x);
|
||
}
|
||
</code></pre>
|
||
<p>And finally, run it:</p>
|
||
<pre><code class="language-bash">$ cargo run
|
||
Compiling bindings v0.1.0 (file:///home/steve/tmp/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’.
|
||
This looks like many languages, but there are some subtleties.
|
||
We create variable bindings with a ‘<code>let</code> statement’, which looks like this:</p>
|
||
<pre><code class="language-text">let PATTERN = VALUE;
|
||
</code></pre>
|
||
<p>In our example, the <code>PATTERN</code> is a humble <code>x</code>, and the <code>VALUE</code> is a simple <code>5</code>.
|
||
The <code>let</code> statement takes the <code>VALUE</code>, and matches it to the <code>PATTERN</code>, creating new bindings.
|
||
Therefore, our example creates a new binding, <code>x</code>, and gives it an initial value of <code>5</code>.
|
||
Patterns are a big part of Rust, we will see them in many places.</p>
|
||
<p>That seems like a lot of explanation for a basic assignment statement!
|
||
The trick is that these patterns can become more complex, and have a lot of power.
|
||
We’ll explore more complex patterns as we learn more.</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!("The value of x is: {}", 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.
|
||
This is why it’s a macro; Rust does not support optional arguments for regular functions.
|
||
The format string can contain the special text <code>{}</code>.
|
||
If it does, it fills in that place in the string with the values of the other arguments.
|
||
In this case, we’ve passed <code>x</code>.
|
||
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 assignment</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!("The value of x is: {}", x);
|
||
println!("The value of y is: {}", 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:///home/steve/tmp/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>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!("The value of x is: {}", 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:///home/steve/tmp/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!("The value of x is: {}", 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:///home/steve/tmp/bindings)
|
||
src/main.rs:4:39: 4:40 error: use of possibly uninitialized variable: `x` [E0381]
|
||
src/main.rs:4 println!(“The value of x is: {}”, x);
|
||
^
|
||
<std macros>:2:25: 2:56 note: in this expansion of format_args!
|
||
<std macros>:3:1: 3:54 note: in this expansion of print! (defined in <std macros>)
|
||
src/main.rs:4:5: 4:42 note: in this expansion of println! (defined in <std macros>)
|
||
src/main.rs:4:39: 4:40 help: run `rustc --explain E0381` to see a detailed explanation
|
||
error: aborting due to previous error
|
||
Could not compile `bindings`.
|
||
|
||
To learn more, run the command again with --verbose.
|
||
</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!("The value of x is: {}", 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:///home/steve/tmp/bindings)
|
||
src/main.rs:4:5: 4:10 error: re-assignment of immutable variable `x` [E0384]
|
||
src/main.rs:4 x = 6;
|
||
^~~~~
|
||
src/main.rs:4:5: 4:10 help: run `rustc --explain E0384` to see a detailed explanation
|
||
src/main.rs:2:9: 2:10 note: prior assignment occurs here
|
||
src/main.rs:2 let x = 5;
|
||
^
|
||
</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!("The value of x is: {}", x);
|
||
|
||
x = 6;
|
||
|
||
println!("The value of x is: {}", x);
|
||
}
|
||
</code></pre>
|
||
<p>Running this, we get:</p>
|
||
<pre><code class="language-bash">$ cargo run
|
||
Compiling bindings v0.1.0 (file:///home/steve/tmp/bindings)
|
||
Running `target/debug/bindings`
|
||
The value of x is: 5
|
||
The value of x is: 6
|
||
</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:///home/steve/tmp/bindings)
|
||
src/main.rs:5:5: 5:10 error: re-assignment of immutable variable `y` [E0384]
|
||
src/main.rs:5 y = 8;
|
||
^~~~~
|
||
src/main.rs:5:5: 5:10 help: run `rustc --explain E0384` to see a detailed explanation
|
||
src/main.rs:2:17: 2:18 note: prior assignment occurs here
|
||
src/main.rs:2 let (mut x, y) = (5, 6);
|
||
^
|
||
</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!("x is not yet in scope");
|
||
|
||
let x = 5;
|
||
println!("x is now in scope");
|
||
|
||
println!("In real code, we’d now do a bunch of work.");
|
||
|
||
println!("x will go out of scope now! The next curly brace is ending the main function.");
|
||
}
|
||
</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!("x is not yet in scope");
|
||
|
||
let x = 5;
|
||
println!("x is now in scope");
|
||
|
||
println!("Let’s start a new scope!");
|
||
|
||
{
|
||
let y = 5;
|
||
println!("y is now in scope");
|
||
println!("x is also still in scope");
|
||
|
||
println!("y will go out of scope now!");
|
||
println!("The next curly brace is ending the scope we started.");
|
||
}
|
||
|
||
println!("x is still in scope, but y is now out of scope and is not usable");
|
||
|
||
println!("x will go out of scope now! The next curly brace is ending the main function.");
|
||
}
|
||
</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!("The value of x is: {}", 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!("The value of x is: {}", x);
|
||
}
|
||
</code></pre>
|
||
<p>This will print:</p>
|
||
<pre><code class="language-bash"> Compiling bindings v0.1.0 (file:///home/steve/tmp/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>fn main() {
|
||
let mut x = 5;
|
||
x = x + 1;
|
||
x = x * 2;
|
||
|
||
println!("The value of x is: {}", x);
|
||
|
||
x = 15;
|
||
|
||
println!("The value of x is: {}", x);
|
||
}
|
||
</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!("The value of x is: {}", x);
|
||
|
||
x = 15;
|
||
|
||
println!("The value of x is: {}", 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:///home/steve/tmp/bindings)
|
||
src/main.rs:8:5: 8:11 error: re-assignment of immutable variable `x` [E0384]
|
||
src/main.rs:8 x = 15;
|
||
^~~~~~
|
||
src/main.rs:8:5: 8:11 help: run `rustc --explain E0384` to see a detailed explanation
|
||
src/main.rs:4:9: 4:10 note: prior assignment occurs here
|
||
src/main.rs:4 let x = x * 2;
|
||
^
|
||
error: aborting due to previous error
|
||
Could not compile `bindings`.
|
||
</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!("Before shadowing, x is: {}", x);
|
||
|
||
{
|
||
let x = 6;
|
||
|
||
println!("Now that x is shadowed, x is: {}", x);
|
||
}
|
||
|
||
println!("After shadowing, x is: {}", 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:///home/steve/tmp/bindings)
|
||
Running `target/debug/bindings`
|
||
Before shadowing, x is: 5
|
||
Now that x is shadowed, x is: 6
|
||
After shadowing, x is: 5
|
||
</code></pre>
|
||
|
||
</div>
|
||
|
||
<!-- Mobile navigation buttons -->
|
||
|
||
<a href="basics.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="basics.html" class="nav-chapters previous">
|
||
<i class="fa fa-angle-left"></i>
|
||
</a>
|
||
|
||
|
||
|
||
<a href="functions.html" class="nav-chapters next">
|
||
<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>
|