Files
book/first-edition/variable-bindings.html
T

306 lines
19 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>Variable Bindings - </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='https://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="https://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="https://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 class="light">
<!-- 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 class="affix"><a href="README.html">Introduction</a></li><li><a href="getting-started.html"><strong>1.</strong> Getting Started</a></li><li><a href="guessing-game.html"><strong>2.</strong> Tutorial: Guessing Game</a></li><li><a href="syntax-and-semantics.html"><strong>3.</strong> Syntax and Semantics</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><li><a href="vectors.html"><strong>3.7.</strong> Vectors</a></li><li><a href="ownership.html"><strong>3.8.</strong> Ownership</a></li><li><a href="references-and-borrowing.html"><strong>3.9.</strong> References and Borrowing</a></li><li><a href="lifetimes.html"><strong>3.10.</strong> Lifetimes</a></li><li><a href="mutability.html"><strong>3.11.</strong> Mutability</a></li><li><a href="structs.html"><strong>3.12.</strong> Structs</a></li><li><a href="enums.html"><strong>3.13.</strong> Enums</a></li><li><a href="match.html"><strong>3.14.</strong> Match</a></li><li><a href="patterns.html"><strong>3.15.</strong> Patterns</a></li><li><a href="method-syntax.html"><strong>3.16.</strong> Method Syntax</a></li><li><a href="strings.html"><strong>3.17.</strong> Strings</a></li><li><a href="generics.html"><strong>3.18.</strong> Generics</a></li><li><a href="traits.html"><strong>3.19.</strong> Traits</a></li><li><a href="drop.html"><strong>3.20.</strong> Drop</a></li><li><a href="if-let.html"><strong>3.21.</strong> if let</a></li><li><a href="trait-objects.html"><strong>3.22.</strong> Trait Objects</a></li><li><a href="closures.html"><strong>3.23.</strong> Closures</a></li><li><a href="ufcs.html"><strong>3.24.</strong> Universal Function Call Syntax</a></li><li><a href="crates-and-modules.html"><strong>3.25.</strong> Crates and Modules</a></li><li><a href="const-and-static.html"><strong>3.26.</strong> <code>const</code> and <code>static</code></a></li><li><a href="attributes.html"><strong>3.27.</strong> Attributes</a></li><li><a href="type-aliases.html"><strong>3.28.</strong> <code>type</code> aliases</a></li><li><a href="casting-between-types.html"><strong>3.29.</strong> Casting between types</a></li><li><a href="associated-types.html"><strong>3.30.</strong> Associated Types</a></li><li><a href="unsized-types.html"><strong>3.31.</strong> Unsized Types</a></li><li><a href="operators-and-overloading.html"><strong>3.32.</strong> Operators and Overloading</a></li><li><a href="deref-coercions.html"><strong>3.33.</strong> Deref coercions</a></li><li><a href="macros.html"><strong>3.34.</strong> Macros</a></li><li><a href="raw-pointers.html"><strong>3.35.</strong> Raw Pointers</a></li><li><a href="unsafe.html"><strong>3.36.</strong> <code>unsafe</code></a></li></ul></li><li><a href="effective-rust.html"><strong>4.</strong> Effective Rust</a></li><li><ul class="section"><li><a href="the-stack-and-the-heap.html"><strong>4.1.</strong> The Stack and the Heap</a></li><li><a href="testing.html"><strong>4.2.</strong> Testing</a></li><li><a href="conditional-compilation.html"><strong>4.3.</strong> Conditional Compilation</a></li><li><a href="documentation.html"><strong>4.4.</strong> Documentation</a></li><li><a href="iterators.html"><strong>4.5.</strong> Iterators</a></li><li><a href="concurrency.html"><strong>4.6.</strong> Concurrency</a></li><li><a href="error-handling.html"><strong>4.7.</strong> Error Handling</a></li><li><a href="choosing-your-guarantees.html"><strong>4.8.</strong> Choosing your Guarantees</a></li><li><a href="ffi.html"><strong>4.9.</strong> FFI</a></li><li><a href="borrow-and-asref.html"><strong>4.10.</strong> Borrow and AsRef</a></li><li><a href="release-channels.html"><strong>4.11.</strong> Release Channels</a></li><li><a href="using-rust-without-the-standard-library.html"><strong>4.12.</strong> Using Rust without the standard library</a></li><li><a href="procedural-macros.html"><strong>4.13.</strong> Procedural Macros (and custom derive)</a></li></ul></li><li><a href="glossary.html"><strong>5.</strong> Glossary</a></li><li><a href="syntax-index.html"><strong>6.</strong> Syntax Index</a></li><li><a href="bibliography.html"><strong>7.</strong> Bibliography</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">
<a class="header" href="variable-bindings.html#variable-bindings" name="variable-bindings"><h1>Variable Bindings</h1></a>
<p>Virtually every non-'Hello World’ Rust program uses <em>variable bindings</em>. They
bind some value to a name, so it can be used later. <code>let</code> is
used to introduce a binding, like this:</p>
<pre><code class="language-rust">fn main() {
let x = 5;
}
</code></pre>
<p>Putting <code>fn main() {</code> in each example is a bit tedious, so we’ll leave that out
in the future. If you’re following along, make sure to edit your <code>main()</code>
function, rather than leaving it off. Otherwise, you’ll get an error.</p>
<a class="header" href="variable-bindings.html#patterns" name="patterns"><h1>Patterns</h1></a>
<p>In many languages, a variable binding would be called a <em>variable</em>, but Rust’s
variable bindings have a few tricks up their sleeves. For example the
left-hand side of a <code>let</code> statement is a ‘<a href="patterns.html">pattern</a>’, not a
variable name. This means we can do things like:</p>
<pre><code class="language-rust">let (x, y) = (1, 2);
</code></pre>
<p>After this statement is evaluated, <code>x</code> will be one, and <code>y</code> will be two.
Patterns are really powerful, and have <a href="patterns.html">their own section</a> in the
book. We don’t need those features for now, so we’ll keep this in the back
of our minds as we go forward.</p>
<a class="header" href="variable-bindings.html#type-annotations" name="type-annotations"><h1>Type annotations</h1></a>
<p>Rust is a statically typed language, which means that we specify our types up
front, and they’re checked at compile time. So why does our first example
compile? Well, Rust has this thing called ‘type inference’. If it can figure
out what the type of something is, Rust doesn’t require you to explicitly type
it out.</p>
<p>We can add the type if we want to, though. Types come after a colon (<code>:</code>):</p>
<pre><code class="language-rust">let x: i32 = 5;
</code></pre>
<p>If I asked you to read this out loud to the rest of the class, you’d say “<code>x</code>
is a binding with the type <code>i32</code> and the value <code>5</code>.”</p>
<p>In this case we chose to represent <code>x</code> as a 32-bit signed integer. Rust has
many different primitive integer types. They begin with <code>i</code> for signed integers
and <code>u</code> for unsigned integers. The possible integer sizes are 8, 16, 32, and 64
bits.</p>
<p>In future examples, we may annotate the type in a comment. The examples will
look like this:</p>
<pre><code class="language-rust">fn main() {
let x = 5; // x: i32
}
</code></pre>
<p>Note the similarities between this annotation and the syntax you use with
<code>let</code>. Including these kinds of comments is not idiomatic Rust, but we'll
occasionally include them to help you understand what the types that Rust
infers are.</p>
<a class="header" href="variable-bindings.html#mutability" name="mutability"><h1>Mutability</h1></a>
<p>By default, bindings are <em>immutable</em>. This code will not compile:</p>
<pre><code class="language-rust ignore">let x = 5;
x = 10;
</code></pre>
<p>It will give you this error:</p>
<pre><code class="language-text">error: re-assignment of immutable variable `x`
x = 10;
^~~~~~~
</code></pre>
<p>If you want a binding to be mutable, you can use <code>mut</code>:</p>
<pre><code class="language-rust">let mut x = 5; // mut x: i32
x = 10;
</code></pre>
<p>There is no single reason that bindings are immutable by default, but we can
think about it through one of Rust’s primary focuses: safety. If you forget to
say <code>mut</code>, the compiler will catch it, and let you know that you have mutated
something you may not have intended to mutate. If bindings were mutable by
default, the compiler would not be able to tell you this. If you <em>did</em> intend
mutation, then the solution is quite easy: add <code>mut</code>.</p>
<p>There are other good reasons to avoid mutable state when possible, but they’re
out of the scope of this guide. In general, you can often avoid explicit
mutation, and so it is preferable in Rust. That said, sometimes, mutation is
what you need, so it’s not forbidden.</p>
<a class="header" href="variable-bindings.html#initializing-bindings" name="initializing-bindings"><h1>Initializing bindings</h1></a>
<p>Rust variable bindings have one more aspect that differs from other languages:
bindings are required to be initialized with a value before you're allowed to
use them.</p>
<p>Let’s try it out. Change your <code>src/main.rs</code> file to look like this:</p>
<pre><code class="language-rust">fn main() {
let x: i32;
println!(&quot;Hello world!&quot;);
}
</code></pre>
<p>You can use <code>cargo build</code> on the command line to build it. You’ll get a
warning, but it will still print &quot;Hello, world!&quot;:</p>
<pre><code class="language-text"> Compiling hello_world v0.0.1 (file:///home/you/projects/hello_world)
src/main.rs:2:9: 2:10 warning: unused variable: `x`, #[warn(unused_variables)]
on by default
src/main.rs:2 let x: i32;
^
</code></pre>
<p>Rust warns us that we never use the variable binding, but since we never use
it, no harm, no foul. Things change if we try to actually use this <code>x</code>,
however. Let’s do that. Change your program to look like this:</p>
<pre><code class="language-rust ignore">fn main() {
let x: i32;
println!(&quot;The value of x is: {}&quot;, x);
}
</code></pre>
<p>And try to build it. You’ll get an error:</p>
<pre><code class="language-bash">$ cargo build
Compiling hello_world v0.0.1 (file:///home/you/projects/hello_world)
src/main.rs:4:39: 4:40 error: use of possibly uninitialized variable: `x`
src/main.rs:4 println!(&quot;The value of x is: {}&quot;, x);
^
note: in expansion of format_args!
&lt;std macros&gt;:2:23: 2:77 note: expansion site
&lt;std macros&gt;:1:1: 3:2 note: in expansion of println!
src/main.rs:4:5: 4:42 note: expansion site
error: aborting due to previous error
Could not compile `hello_world`.
</code></pre>
<p>Rust will not let us use a value that has not been initialized.</p>
<p>Let us take a minute to talk about this stuff we've added to <code>println!</code>.</p>
<p>If you include two curly braces (<code>{}</code>, some call them moustaches...) in your
string to print, Rust will interpret this as a request to interpolate some sort
of value. <em>String interpolation</em> is a computer science term that means &quot;stick
in the middle of a string.&quot; We add a comma, and then <code>x</code>, to indicate that we
want <code>x</code> to be the value we’re interpolating. The comma is used to separate
arguments we pass to functions and macros, if you’re passing more than one.</p>
<p>When you use the curly braces, Rust will attempt to display the value in a
meaningful way by checking out its type. If you want to specify the format in a
more detailed manner, there are a <a href="../std/fmt/index.html">wide number of options available</a>.
For now, we'll stick to the default: integers aren't very complicated to
print.</p>
<a class="header" href="variable-bindings.html#scope-and-shadowing" name="scope-and-shadowing"><h1>Scope and shadowing</h1></a>
<p>Let’s get back to bindings. Variable bindings have a scope - they are
constrained to live in the block they were defined in. A block is a collection
of statements enclosed by <code>{</code> and <code>}</code>. Function definitions are also blocks!
In the following example we define two variable bindings, <code>x</code> and <code>y</code>, which
live in different blocks. <code>x</code> can be accessed from inside the <code>fn main() {}</code>
block, while <code>y</code> can be accessed only from inside the inner block:</p>
<pre><code class="language-rust ignore">fn main() {
let x: i32 = 17;
{
let y: i32 = 3;
println!(&quot;The value of x is {} and value of y is {}&quot;, x, y);
}
println!(&quot;The value of x is {} and value of y is {}&quot;, x, y); // This won't work.
}
</code></pre>
<p>The first <code>println!</code> would print &quot;The value of x is 17 and the value of y is
3&quot;, but this example cannot be compiled successfully, because the second
<code>println!</code> cannot access the value of <code>y</code>, since it is not in scope anymore.
Instead we get this error:</p>
<pre><code class="language-bash">$ cargo build
Compiling hello v0.1.0 (file:///home/you/projects/hello_world)
main.rs:7:62: 7:63 error: unresolved name `y`. Did you mean `x`? [E0425]
main.rs:7 println!(&quot;The value of x is {} and value of y is {}&quot;, x, y); // This won't work.
^
note: in expansion of format_args!
&lt;std macros&gt;:2:25: 2:56 note: expansion site
&lt;std macros&gt;:1:1: 2:62 note: in expansion of print!
&lt;std macros&gt;:3:1: 3:54 note: expansion site
&lt;std macros&gt;:1:1: 3:58 note: in expansion of println!
main.rs:7:5: 7:65 note: expansion site
main.rs:7:62: 7:63 help: run `rustc --explain E0425` to see a detailed explanation
error: aborting due to previous error
Could not compile `hello`.
To learn more, run the command again with --verbose.
</code></pre>
<p>Additionally, variable bindings can be shadowed. This means that a later
variable binding with the same name as another binding that is currently in
scope will override the previous binding.</p>
<pre><code class="language-rust">let x: i32 = 8;
{
println!(&quot;{}&quot;, x); // Prints &quot;8&quot;.
let x = 12;
println!(&quot;{}&quot;, x); // Prints &quot;12&quot;.
}
println!(&quot;{}&quot;, x); // Prints &quot;8&quot;.
let x = 42;
println!(&quot;{}&quot;, x); // Prints &quot;42&quot;.
</code></pre>
<p>Shadowing and mutable bindings may appear as two sides of the same coin, but
they are two distinct concepts that can't always be used interchangeably. For
one, shadowing enables us to rebind a name to a value of a different type. It
is also possible to change the mutability of a binding. Note that shadowing a
name does not alter or destroy the value it was bound to, and the value will
continue to exist until it goes out of scope, even if it is no longer accessible
by any means.</p>
<pre><code class="language-rust">let mut x: i32 = 1;
x = 7;
let x = x; // `x` is now immutable and is bound to `7`.
let y = 4;
let y = &quot;I can also be bound to text!&quot;; // `y` is now of a different type.
</code></pre>
</div>
<!-- Mobile navigation buttons -->
<a href="syntax-and-semantics.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="syntax-and-semantics.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>
<!-- Livereload script (if served using the cli tool) -->
<script src="highlight.js"></script>
<script src="book.js"></script>
</body>
</html>