mirror of
https://github.com/rust-lang/book.git
synced 2026-11-30 20:14:32 -06:00
298 lines
19 KiB
HTML
298 lines
19 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>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, just 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>
|
||
<h1>Patterns</h1>
|
||
<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> expression is a ‘<a href="patterns.html">pattern</a>’, not just 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 expression 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 just keep this in the back
|
||
of our minds as we go forward.</p>
|
||
<h1>Type annotations</h1>
|
||
<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 actually 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>five</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>
|
||
<h1>Mutability</h1>
|
||
<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 verboten.</p>
|
||
<h1>Initializing bindings</h1>
|
||
<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!("Hello world!");
|
||
}
|
||
</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 "Hello, world!":</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_variable)]
|
||
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!("The value of x is: {}", 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!("The value of x is: {}", x);
|
||
^
|
||
note: in expansion of format_args!
|
||
<std macros>:2:23: 2:77 note: expansion site
|
||
<std macros>: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. Next, let’s
|
||
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 "stick
|
||
in the middle of a string." 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 just 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 just stick to the default: integers aren't very complicated to
|
||
print.</p>
|
||
<h1>Scope and shadowing</h1>
|
||
<p>Let’s get back to bindings. Variable bindings have a scope - they are
|
||
constrained to live in a 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!("The value of x is {} and value of y is {}", x, y);
|
||
}
|
||
println!("The value of x is {} and value of y is {}", x, y); // This won't work
|
||
}
|
||
</code></pre>
|
||
<p>The first <code>println!</code> would print "The value of x is 17 and the value of y is
|
||
3", 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!("The value of x is {} and value of y is {}", x, y); // This won't work
|
||
^
|
||
note: in expansion of format_args!
|
||
<std macros>:2:25: 2:56 note: expansion site
|
||
<std macros>:1:1: 2:62 note: in expansion of print!
|
||
<std macros>:3:1: 3:54 note: expansion site
|
||
<std macros>: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's currently in
|
||
scope, will override the previous binding.</p>
|
||
<pre><code class="language-rust">let x: i32 = 8;
|
||
{
|
||
println!("{}", x); // Prints "8"
|
||
let x = 12;
|
||
println!("{}", x); // Prints "12"
|
||
}
|
||
println!("{}", x); // Prints "8"
|
||
let x = 42;
|
||
println!("{}", x); // Prints "42"
|
||
</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.</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 = "I can also be bound to text!"; // y is now of a different type
|
||
</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>
|