mirror of
https://github.com/rust-lang/book.git
synced 2026-11-30 20:24:32 -06:00
rebuild pages at 2067b6e
This commit is contained in:
+35
-35
@@ -96,12 +96,12 @@ $ cd hello_world
|
||||
> cd hello_world
|
||||
</code></pre>
|
||||
<h3>Writing and Running a Rust Program</h3>
|
||||
<p>Next, make a new source file and call it <code>main.rs</code>. Rust files always end with
|
||||
the <code>.rs</code> extension. If you’re using more than one word in your filename, use
|
||||
an underscore to separate them. For example, you'd use <code>hello_world.rs</code> rather
|
||||
than <code>helloworld.rs</code>.</p>
|
||||
<p>Now open the <code>main.rs</code> file you just created, and type the following code:</p>
|
||||
<p>Filename: main.rs</p>
|
||||
<p>Next, make a new source file and call it <em>main.rs</em>. Rust files always end with
|
||||
the <em>.rs</em> extension. If you’re using more than one word in your filename, use
|
||||
an underscore to separate them. For example, you'd use <em>hello_world.rs</em> rather
|
||||
than <em>helloworld.rs</em>.</p>
|
||||
<p>Now open the <em>main.rs</em> file you just created, and type the following code:</p>
|
||||
<p><span class="filename">Filename: main.rs</span></p>
|
||||
<pre><code class="language-rust">fn main() {
|
||||
println!("Hello, world!");
|
||||
}
|
||||
@@ -169,12 +169,12 @@ main main.rs
|
||||
main.exe
|
||||
main.rs
|
||||
</code></pre>
|
||||
<p>This shows we have two files: the source code, with the <code>.rs</code> extension, and the
|
||||
executable (<code>main.exe</code> on Windows, <code>main</code> everywhere else). All that's left to
|
||||
do from here is run the <code>main</code> or <code>main.exe</code> file, like this:</p>
|
||||
<p>This shows we have two files: the source code, with the <em>.rs</em> extension, and the
|
||||
executable (<em>main.exe</em> on Windows, <em>main</em> everywhere else). All that's left to
|
||||
do from here is run the <em>main</em> or <em>main.exe</em> file, like this:</p>
|
||||
<pre><code class="language-text">$ ./main # or .\main.exe on Windows
|
||||
</code></pre>
|
||||
<p>If <code>main.rs</code> were your "Hello, world!" program, this would print <code>Hello, world!</code> to your terminal.</p>
|
||||
<p>If <em>main.rs</em> were your "Hello, world!" program, this would print <code>Hello, world!</code> to your terminal.</p>
|
||||
<p>If you come from a dynamic language like Ruby, Python, or JavaScript, you may
|
||||
not be used to compiling and running a program being separate steps. Rust is an
|
||||
<em>ahead-of-time compiled</em> language, which means that you can compile a program,
|
||||
@@ -227,15 +227,15 @@ executable application, as opposed to a library. Executables are binary
|
||||
executable files often called just <em>binaries</em>. We've given <code>hello_cargo</code>
|
||||
as the name for our project, and Cargo creates its files in a directory
|
||||
of the same name that we can then go into.</p>
|
||||
<p>If we list the files in the <code>hello_cargo</code> directory, we can see that Cargo has
|
||||
generated two files and one directory for us: a <code>Cargo.toml</code> and a <code>src</code>
|
||||
directory with a <code>main.rs</code> file inside. It has also initialized a new <code>git</code>
|
||||
repository in the <code>hello_cargo</code> directory for us, along with a <code>.gitignore</code>
|
||||
<p>If we list the files in the <em>hello_cargo</em> directory, we can see that Cargo has
|
||||
generated two files and one directory for us: a <em>Cargo.toml</em> and a <em>src</em>
|
||||
directory with a <em>main.rs</em> file inside. It has also initialized a new git
|
||||
repository in the <em>hello_cargo</em> directory for us, along with a <em>.gitignore</em>
|
||||
file; you can change this to use a different version control system, or no
|
||||
version control system, by using the <code>--vcs</code> flag.</p>
|
||||
<p>Open up <code>Cargo.toml</code> in your text editor of choice. It should look something
|
||||
<p>Open up <em>Cargo.toml</em> in your text editor of choice. It should look something
|
||||
like this:</p>
|
||||
<p>Filename: Cargo.toml</p>
|
||||
<p><span class="filename">Filename: Cargo.toml</span></p>
|
||||
<pre><code class="language-toml">[package]
|
||||
name = "hello_cargo"
|
||||
version = "0.1.0"
|
||||
@@ -259,8 +259,8 @@ file.</p>
|
||||
depend on so that Cargo knows to download and compile those too. We won't need
|
||||
any other crates for this project, but we will in the guessing game tutorial in
|
||||
the next chapter.</p>
|
||||
<p>Now let's look at <code>src/main.rs</code>:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p>Now let's look at <em>src/main.rs</em>:</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust">fn main() {
|
||||
println!("Hello, world!");
|
||||
}
|
||||
@@ -269,41 +269,41 @@ the next chapter.</p>
|
||||
earlier! So that part is the same. The differences between our previous project
|
||||
and the project generated by Cargo that we've seen so far are:</p>
|
||||
<ul>
|
||||
<li>Our code goes in the <code>src</code> directory</li>
|
||||
<li>The top level contains a <code>Cargo.toml</code> configuration file</li>
|
||||
<li>Our code goes in the <em>src</em> directory</li>
|
||||
<li>The top level contains a <em>Cargo.toml</em> configuration file</li>
|
||||
</ul>
|
||||
<p>Cargo expects your source files to live inside the <code>src</code> directory so that the
|
||||
<p>Cargo expects your source files to live inside the <em>src</em> directory so that the
|
||||
top-level project directory is just for READMEs, license information,
|
||||
configuration files, and anything else not related to your code. In this way,
|
||||
using Cargo helps you keep your projects nice and tidy. There's a place for
|
||||
everything, and everything is in its place.</p>
|
||||
<p>If you started a project that doesn't use Cargo, as we did with our project in
|
||||
the <code>hello_world</code> directory, you can convert it to a project that does use
|
||||
Cargo by moving your code into the <code>src</code> directory and creating an appropriate
|
||||
<code>Cargo.toml</code>.</p>
|
||||
the <em>hello_world</em> directory, you can convert it to a project that does use
|
||||
Cargo by moving your code into the <em>src</em> directory and creating an appropriate
|
||||
<em>Cargo.toml</em>.</p>
|
||||
<h3>Building and Running a Cargo Project</h3>
|
||||
<p>Now let's look at what's different about building and running your Hello World
|
||||
program through Cargo! To do so, enter the following commands:</p>
|
||||
<pre><code class="language-text">$ cargo build
|
||||
Compiling hello_cargo v0.1.0 (file:///projects/hello_cargo)
|
||||
</code></pre>
|
||||
<p>This should have created an executable file in <code>target/debug/hello_cargo</code> (or
|
||||
<code>target\debug\hello_cargo.exe</code> on Windows), which you can run with this command:</p>
|
||||
<p>This should have created an executable file in <em>target/debug/hello_cargo</em> (or
|
||||
<em>target\debug\hello_cargo.exe</em> on Windows), which you can run with this command:</p>
|
||||
<pre><code class="language-text">$ ./target/debug/hello_cargo # or .\target\debug\hello_cargo.exe on Windows
|
||||
Hello, world!
|
||||
</code></pre>
|
||||
<p>Bam! If all goes well, <code>Hello, world!</code> should print to the terminal once more.</p>
|
||||
<p>Running <code>cargo build</code> for the first time also causes Cargo to create a new file
|
||||
at the top level called <code>Cargo.lock</code>, which looks like this:</p>
|
||||
<p>Filename: Cargo.lock</p>
|
||||
at the top level called <em>Cargo.lock</em>, which looks like this:</p>
|
||||
<p><span class="filename">Filename: Cargo.lock</span></p>
|
||||
<pre><code class="language-toml">[root]
|
||||
name = "hello_cargo"
|
||||
version = "0.1.0"
|
||||
</code></pre>
|
||||
<p>Cargo uses the <code>Cargo.lock</code> file to keep track of dependencies in your
|
||||
application. This project doesn't have dependencies, so the file is a bit
|
||||
sparse. Realistically, you won't ever need to touch this file yourself; just
|
||||
let Cargo handle it.</p>
|
||||
<p>Cargo uses the <em>Cargo.lock</em> to keep track of dependencies in your application.
|
||||
This project doesn't have dependencies, so the file is a bit sparse.
|
||||
Realistically, you won't ever need to touch this file yourself; just let Cargo
|
||||
handle it.</p>
|
||||
<p>We just built a project with <code>cargo build</code> and ran it with
|
||||
<code>./target/debug/hello_cargo</code>, but we can also use <code>cargo run</code> to compile
|
||||
and then run:</p>
|
||||
@@ -326,21 +326,21 @@ Hello, world!
|
||||
<li>Instead of using <code>rustc</code>, build a project using <code>cargo build</code> (or build and
|
||||
run it in one step with <code>cargo run</code>)</li>
|
||||
<li>Instead of the result of the build being put in the same directory as our
|
||||
code, Cargo will put it in the <code>target/debug</code> directory.</li>
|
||||
code, Cargo will put it in the <em>target/debug</em> directory.</li>
|
||||
</ul>
|
||||
<p>The other advantage of using Cargo is that the commands are the same no matter
|
||||
what operating system you're on, so at this point we will no longer be
|
||||
providing specific instructions for Linux and Mac versus Windows.</p>
|
||||
<h3>Building for Release</h3>
|
||||
<p>When your project is finally ready for release, you can use <code>cargo build --release</code> to compile your project with optimizations. This will create an
|
||||
executable in <code>target/release</code> instead of <code>target/debug</code>. These optimizations
|
||||
executable in <em>target/release</em> instead of <em>target/debug</em>. These optimizations
|
||||
make your Rust code run faster, but turning them on makes your program take
|
||||
longer to compile. This is why there are two different profiles: one for
|
||||
development when you want to be able to rebuild quickly and often, and one for
|
||||
building the final program you’ll give to a user that won't be rebuilt and
|
||||
that we want to run as fast as possible. If you're benchmarking the running
|
||||
time of your code, be sure to run <code>cargo build --release</code> and benchmark with
|
||||
the executable in <code>target/release</code>.</p>
|
||||
the executable in <em>target/release</em>.</p>
|
||||
<h3>Cargo as Convention</h3>
|
||||
<p>With simple projects, Cargo doesn't provide a whole lot of value over just
|
||||
using <code>rustc</code>, but it will prove its worth as you continue. With complex
|
||||
|
||||
@@ -89,7 +89,7 @@ as the first argument. The <code>--bin</code> flag tells Cargo to make a binary
|
||||
similar to the one in Chapter 1. The second command changes to the new
|
||||
project’s directory.</p>
|
||||
<p>Look at the generated <em>Cargo.toml</em> file:</p>
|
||||
<p>Filename: Cargo.toml</p>
|
||||
<p><span class="filename">Filename: Cargo.toml</span></p>
|
||||
<pre><code class="language-toml">[package]
|
||||
name = "guessing_game"
|
||||
version = "0.1.0"
|
||||
@@ -101,7 +101,7 @@ authors = ["Your Name <you@example.com>"]
|
||||
correct, fix that in the file and save it again.</p>
|
||||
<p>As you saw in Chapter 1, <code>cargo new</code> generates a “Hello, world!” program for
|
||||
you. Check out the <em>src/main.rs</em> file:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust">fn main() {
|
||||
println!("Hello, world!");
|
||||
}
|
||||
@@ -121,7 +121,8 @@ before moving on to the next one.</p>
|
||||
<p>The first part of the program will ask for user input, process that input, and
|
||||
check that the input is in the expected form. To start, we’ll allow the player
|
||||
to input a guess. Enter the code in Listing 2-1 into <em>src/main.rs</em>.</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<figure>
|
||||
<span class="filename">Filename: src/main.rs</span>
|
||||
<pre><code class="language-rust,ignore">use std::io;
|
||||
|
||||
fn main() {
|
||||
@@ -137,9 +138,10 @@ fn main() {
|
||||
println!("You guessed: {}", guess);
|
||||
}
|
||||
</code></pre>
|
||||
<caption>
|
||||
Listing 2-1: Code to get a guess from the user and print it out
|
||||
</caption>
|
||||
<figcaption>
|
||||
<p>Listing 2-1: Code to get a guess from the user and print it out</p>
|
||||
</figcaption>
|
||||
</figure>
|
||||
<p>This code contains a lot of information, so let’s go over it bit by bit. To
|
||||
obtain user input and then print the result as output, we need to import the
|
||||
<code>io</code> (input/output) library from the standard library (which is known as <code>std</code>):</p>
|
||||
@@ -316,7 +318,7 @@ code that uses <code>rand</code>, we need to modify the <em>Cargo.toml</em> file
|
||||
<code>rand</code> crate as a dependency. Open that file now and add the following line to
|
||||
the bottom beneath the <code>[dependencies]</code> section header that Cargo created for
|
||||
you:</p>
|
||||
<p>Filename: Cargo.toml</p>
|
||||
<p><span class="filename">Filename: Cargo.toml</span></p>
|
||||
<pre><code class="language-toml">[dependencies]
|
||||
|
||||
rand = "0.3.14"
|
||||
@@ -332,6 +334,7 @@ for <code>^0.3.14</code>, which means “any version that has a public API compa
|
||||
version 0.3.14.”</p>
|
||||
<p>Now, without changing any of the code, let’s build the project, as shown in
|
||||
Listing 2-2:</p>
|
||||
<figure>
|
||||
<pre><code class="language-text">$ cargo build
|
||||
Updating registry `https://github.com/rust-lang/crates.io-index`
|
||||
Downloading rand v0.3.14
|
||||
@@ -340,10 +343,11 @@ Listing 2-2:</p>
|
||||
Compiling rand v0.3.14
|
||||
Compiling guessing_game v0.1.0 (file:///projects/guessing_game)
|
||||
</code></pre>
|
||||
<caption>
|
||||
Listing 2-2: The output from running `cargo build` after adding the rand crate
|
||||
as a dependency
|
||||
</caption>
|
||||
<figcaption>
|
||||
<p>Listing 2-2: The output from running <code>cargo build</code> after adding the rand crate
|
||||
as a dependency</p>
|
||||
</figcaption>
|
||||
</figure>
|
||||
<p>You may see different version numbers (but they will all be compatible with
|
||||
the code, thanks to SemVer!), and the lines may be in a different order.</p>
|
||||
<p>Now that we have an external dependency, Cargo fetches the latest versions of
|
||||
@@ -420,7 +424,8 @@ number of packages.</p>
|
||||
<h3>Generating a Random Number</h3>
|
||||
<p>Let’s start <em>using</em> <code>rand</code>. The next step is to update <em>src/main.rs</em>, as shown
|
||||
in Listing 2-3:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<figure>
|
||||
<span class="filename">Filename: src/main.rs</span>
|
||||
<pre><code class="language-rust,ignore">extern crate rand;
|
||||
|
||||
use std::io;
|
||||
@@ -443,9 +448,10 @@ fn main() {
|
||||
println!("You guessed: {}", guess);
|
||||
}
|
||||
</code></pre>
|
||||
<caption>
|
||||
Listing 2-3: Code changes needed in order to generate a random number
|
||||
</caption>
|
||||
<figcaption>
|
||||
<p>Listing 2-3: Code changes needed in order to generate a random number</p>
|
||||
</figcaption>
|
||||
</figure>
|
||||
<p>We’re adding a <code>extern crate rand;</code> line to the top that lets Rust know we’ll be
|
||||
using that external dependency. This also does the equivalent of calling <code>use rand</code>, so now we can call anything in the <code>rand</code> crate by prefixing it with
|
||||
<code>rand::</code>.</p>
|
||||
@@ -493,7 +499,8 @@ You guessed: 5
|
||||
<h2>Comparing the Guess to the Secret Number</h2>
|
||||
<p>Now that we have user input and a random number, we can compare them. That
|
||||
step is shown in Listing 2-4:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<figure>
|
||||
<span class="filename">Filename: src/main.rs</span>
|
||||
<pre><code class="language-rust,ignore">extern crate rand;
|
||||
|
||||
use std::io;
|
||||
@@ -523,9 +530,10 @@ fn main() {
|
||||
}
|
||||
}
|
||||
</code></pre>
|
||||
<caption>
|
||||
Listing 2-4: Handling the possible return values of comparing two numbers
|
||||
</caption>
|
||||
<figcaption>
|
||||
<p>Listing 2-4: Handling the possible return values of comparing two numbers</p>
|
||||
</figcaption>
|
||||
</figure>
|
||||
<p>The first new bit here is another <code>use</code>, bringing a type called
|
||||
<code>std::cmp::Ordering</code> into scope from the standard library. <code>Ordering</code> is
|
||||
another enum, like <code>Result</code>, but the variants for <code>Ordering</code> are <code>Less</code>,
|
||||
@@ -591,7 +599,7 @@ not compare a string and a number type.</p>
|
||||
<p>Ultimately, we want to convert the <code>String</code> the program reads as input into a
|
||||
real number type so we can compare it to the guess numerically. We can do
|
||||
that by adding the following two lines to the <code>main</code> function body:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust,ignore">extern crate rand;
|
||||
|
||||
use std::io;
|
||||
@@ -684,7 +692,7 @@ Let’s change that by adding a loop!</p>
|
||||
<h2>Allowing Multiple Guesses with Looping</h2>
|
||||
<p>The <code>loop</code> keyword gives us an infinite loop. Add that now to give users more
|
||||
chances at guessing the number:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust,ignore">extern crate rand;
|
||||
|
||||
use std::io;
|
||||
@@ -757,7 +765,7 @@ However, this is suboptimal to say the least. We want the game to automatically
|
||||
stop when the correct number is guessed.</p>
|
||||
<h3>Quitting After a Correct Guess</h3>
|
||||
<p>Let’s program the game to quit when the user wins by adding a <code>break</code>:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust,ignore">extern crate rand;
|
||||
|
||||
use std::io;
|
||||
@@ -853,7 +861,8 @@ You win!
|
||||
that the program is still printing out the secret number. That worked well for
|
||||
testing, but it ruins the game. Let’s delete the <code>println!</code> that outputs the
|
||||
secret number. Listing 2-5 shows the final code:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<figure>
|
||||
<span class="filename">Filename: src/main.rs</span>
|
||||
<pre><code class="language-rust,ignore">extern crate rand;
|
||||
|
||||
use std::io;
|
||||
@@ -891,9 +900,10 @@ fn main() {
|
||||
}
|
||||
}
|
||||
</code></pre>
|
||||
<caption>
|
||||
Listing 2-5: Complete code of the guessing game
|
||||
</caption>
|
||||
<figcaption>
|
||||
<p>Listing 2-5: Complete code of the guessing game</p>
|
||||
</figcaption>
|
||||
</figure>
|
||||
<h2>Summary</h2>
|
||||
<p>At this point, you’ve successfully built the guessing game! Congratulations!</p>
|
||||
<p>This project was a hands-on way to introduce you to many new Rust concepts:
|
||||
|
||||
@@ -76,6 +76,7 @@ but we’ll discuss them in the context of Rust and explain their conventions.</
|
||||
and control flow. These foundations will be in every Rust program, and learning
|
||||
them early will give you a strong core to start from.</p>
|
||||
<!-- PROD: START BOX -->
|
||||
<blockquote>
|
||||
<h3>Keywords</h3>
|
||||
<p>The Rust language has a set of <em>keywords</em> that have been reserved for use by
|
||||
the language only, much like other languages do. Keep in mind that you cannot
|
||||
@@ -84,6 +85,7 @@ special meanings, and you’ll be using them to do various tasks in your Rust
|
||||
programs; a few have no current functionality associated with them but have
|
||||
been reserved for functionality that might be added to Rust in the future. You
|
||||
can find a list of the keywords in Appendix A.</p>
|
||||
</blockquote>
|
||||
<!-- PROD: END BOX -->
|
||||
|
||||
</div>
|
||||
|
||||
@@ -78,7 +78,7 @@ you can’t change that value. To illustrate, let’s generate a new project cal
|
||||
<em>variables</em> in your <em>projects</em> directory by using <code>cargo new --bin variables</code>.</p>
|
||||
<p>Then, in your new <em>variables</em> directory, open <em>src/main.rs</em> and replace its
|
||||
code with the following:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust,ignore">fn main() {
|
||||
let x = 5;
|
||||
println!("The value of x is: {}", x);
|
||||
@@ -122,7 +122,7 @@ addition to allowing this value to change, it conveys intent to future readers
|
||||
of the code by indicating that other parts of the code will be changing this
|
||||
variable value.</p>
|
||||
<p>For example, change <em>src/main.rs</em> to the following:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust">fn main() {
|
||||
let mut x = 5;
|
||||
println!("The value of x is: {}", x);
|
||||
@@ -182,7 +182,7 @@ variables with the same name as a previous variables, and the new variable
|
||||
<em>shadowed</em> by the second, which means that the second variable’s value is what
|
||||
we’ll see when we use the variable. We can shadow a variable by using the same
|
||||
variable’s name and repeating the use of the <code>let</code> keyword as follows:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust">fn main() {
|
||||
let x = 5;
|
||||
|
||||
|
||||
+20
-16
@@ -104,9 +104,10 @@ that the value it’s associated with should be a signed integer (hence the <cod
|
||||
as opposed to a <code>u</code> for unsigned) for a 32-bit system. Table 3-1 shows the
|
||||
built-in integer types in Rust. Each variant in the Signed and Unsigned columns
|
||||
(for example, <em>i32</em>) can be used to declare the type of an integer value.</p>
|
||||
<caption>
|
||||
Table 3-1: Integer Types in Rust
|
||||
</caption>
|
||||
<figure>
|
||||
<figcaption>
|
||||
<p>Table 3-1: Integer Types in Rust</p>
|
||||
</figcaption>
|
||||
<table><thead><tr><td> Length </td><td> Signed </td><td> Unsigned </td></tr></thead>
|
||||
<tr><td> 8-bit </td><td> i8 </td><td> u8 </td></tr>
|
||||
<tr><td> 16-bit </td><td> i16 </td><td> u16 </td></tr>
|
||||
@@ -114,6 +115,7 @@ Table 3-1: Integer Types in Rust
|
||||
<tr><td> 64-bit </td><td> i64 </td><td> u64 </td></tr>
|
||||
<tr><td> arch </td><td> isize </td><td> usize </td></tr>
|
||||
</table>
|
||||
</figure>
|
||||
<p>Each variant can be either signed or unsigned and has an explicit size.
|
||||
Signed and unsigned refers to whether it’s possible for the number to be
|
||||
negative or positive; in other words, whether the number needs to have a sign
|
||||
@@ -135,9 +137,10 @@ if you’re on a 32-bit architecture.</p>
|
||||
<p>You can write integer literals in any of the forms shown in Table 3-2. Note
|
||||
that all number literals except the byte literal allow a type suffix, such as
|
||||
<code>57u8</code>, and <code>_</code> as a visual separator, such as <code>1_000</code>.</p>
|
||||
<caption>
|
||||
Table 3-2: Integer Literals in Rust
|
||||
</caption>
|
||||
<figure>
|
||||
<figcaption>
|
||||
<p>Table 3-2: Integer Literals in Rust</p>
|
||||
</figcaption>
|
||||
<table><thead><tr><td> Number literals </td><td> Example </td></tr></thead>
|
||||
<tr><td> Decimal </td><td> <code>98_222</code> </td></tr>
|
||||
<tr><td> Hex </td><td> <code>0xff</code> </td></tr>
|
||||
@@ -145,6 +148,7 @@ Table 3-2: Integer Literals in Rust
|
||||
<tr><td> Binary </td><td> <code>0b1111_0000</code> </td></tr>
|
||||
<tr><td> Byte (<code>u8</code> only) </td><td> <code>b'A'</code> </td></tr>
|
||||
</table>
|
||||
</figure>
|
||||
<p>So how do you know which type of integer to use? If you’re unsure, Rust’s
|
||||
defaults are generally good choices, and integer types default to <code>i32</code>: it’s
|
||||
generally the fastest, even on 64-bit systems. The primary situation in which
|
||||
@@ -160,7 +164,7 @@ worse performance for better precision is a reasonable initial choice, and you
|
||||
should benchmark your code if you suspect floating-point size is a problem in
|
||||
your situation.</p>
|
||||
<p>Here’s an example that shows floating-point numbers in action:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust">fn main() {
|
||||
let x = 2.0; // f64
|
||||
|
||||
@@ -173,7 +177,7 @@ your situation.</p>
|
||||
<p>Rust supports the usual basic mathematic operations you’d expect for all of the
|
||||
number types: addition, subtraction, multiplication, division, and remainder.
|
||||
The following code shows how you’d use each one in a <code>let</code> statement:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust">fn main() {
|
||||
// addition
|
||||
let sum = 5 + 10;
|
||||
@@ -198,7 +202,7 @@ list of all operators that Rust provides.</p>
|
||||
<p>As in most other programming languages, a boolean type in Rust has two possible
|
||||
values: <code>true</code> and <code>false</code>. The boolean type in Rust is specified using <code>bool</code>.
|
||||
For example:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust">fn main() {
|
||||
let t = true;
|
||||
|
||||
@@ -212,7 +216,7 @@ section.</p>
|
||||
<p>So far we’ve only worked with numbers, but Rust supports letters too. Rust’s
|
||||
<code>char</code> type is the language’s most primitive alphabetic type, and the following
|
||||
code shows one way to use it:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust">fn main() {
|
||||
let c = 'z';
|
||||
let z = 'ℤ';
|
||||
@@ -237,7 +241,7 @@ a variety of types into one compound type.</p>
|
||||
parentheses. Each position in the tuple has a type, and the types of the
|
||||
different values in the tuple don’t have to be the same. We’ve added optional
|
||||
type annotations in this example:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust">fn main() {
|
||||
let tup: (i32, f64, u8) = (500, 6.4, 1);
|
||||
}
|
||||
@@ -245,7 +249,7 @@ type annotations in this example:</p>
|
||||
<p>The variable <code>tup</code> binds to the entire tuple, since a tuple is considered a
|
||||
single compound element. To get the individual values out of a tuple, we can
|
||||
use pattern matching to destructure a tuple value, like this:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust">fn main() {
|
||||
let tup = (500, 6.4, 1);
|
||||
|
||||
@@ -262,7 +266,7 @@ the single tuple into three parts. Finally, the program prints the value of
|
||||
<p>In addition to destructuring through pattern matching, we can also access a
|
||||
tuple element directly by using a period (<code>.</code>) followed by the index of the
|
||||
value we want to access. For example:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust">fn main() {
|
||||
let x: (i32, f64, u8) = (500, 6.4, 1);
|
||||
|
||||
@@ -283,7 +287,7 @@ different than arrays in some other languages because arrays in Rust have a
|
||||
fixed length: once declared, they cannot grow or shrink in size.</p>
|
||||
<p>In Rust, the values going into an array are written as a comma-separated list
|
||||
inside square brackets:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust">fn main() {
|
||||
let a = [1, 2, 3, 4, 5];
|
||||
}
|
||||
@@ -305,7 +309,7 @@ an array because you know it will always contain 12 items:</p>
|
||||
<h5>Accessing Array Elements</h5>
|
||||
<p>An array is a single chunk of memory allocated on the stack. We can access
|
||||
elements of an array using indexing, like this:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust">fn main() {
|
||||
let a = [1, 2, 3, 4, 5];
|
||||
|
||||
@@ -319,7 +323,7 @@ get the value <code>2</code> from index <code>[1]</code> in the array.</p>
|
||||
<h5>Invalid Array Element Access</h5>
|
||||
<p>What happens if we try to access an element of an array that is past the end of
|
||||
the array? Say we change the example to the following:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust,ignore">fn main() {
|
||||
let a = [1, 2, 3, 4, 5];
|
||||
|
||||
|
||||
@@ -75,7 +75,7 @@ declare new functions.</p>
|
||||
<p>Rust code uses <em>snake case</em> as the conventional style for function and variable
|
||||
names. In snake case, all letters are lowercase and underscores separate words.
|
||||
Here’s a program that contains an example function definition:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust">fn main() {
|
||||
println!("Hello, world!");
|
||||
|
||||
@@ -110,7 +110,7 @@ called and its message is printed.</p>
|
||||
<h3>Function Arguments</h3>
|
||||
<p>Functions can also take arguments. The following rewritten version of
|
||||
<code>another_function</code> shows what arguments look like in Rust:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust">fn main() {
|
||||
another_function(5);
|
||||
}
|
||||
@@ -135,7 +135,7 @@ means the compiler almost never needs you to use them elsewhere in the code to
|
||||
figure out what you mean.</p>
|
||||
<p>When you want a function to have multiple arguments, separate them inside the
|
||||
function signature with commas, like this:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust">fn main() {
|
||||
another_function(5, 6);
|
||||
}
|
||||
@@ -174,19 +174,21 @@ instructions that perform some action and do not return a value. <em>Expressions
|
||||
evaluate to a resulting value. Let’s look at some examples.</p>
|
||||
<p>Creating a variable and assigning a value to it with the <code>let</code> keyword is a
|
||||
statement. In Listing 3-3, <code>let y = 6;</code> is a statement:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<figure>
|
||||
<span class="filename">Filename: src/main.rs</span>
|
||||
<pre><code class="language-rust">fn main() {
|
||||
let y = 6;
|
||||
}
|
||||
</code></pre>
|
||||
<caption>
|
||||
Listing 3-3: A `main` function declaration containing one statement.
|
||||
</caption>
|
||||
<figcaption>
|
||||
<p>Listing 3-3: A <code>main</code> function declaration containing one statement.</p>
|
||||
</figcaption>
|
||||
</figure>
|
||||
<p>Function definitions are also statements; the entire preceding example is a
|
||||
statement in itself.</p>
|
||||
<p>Statements do not return values. Therefore, you can’t assign a <code>let</code> statement
|
||||
to another variable, as the following code tries to do:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust,ignore">fn main() {
|
||||
let x = (let y = 6);
|
||||
}
|
||||
@@ -214,7 +216,7 @@ statements: in Listing 3-3 that had the statement <code>let y = 6;</code>, <code
|
||||
expression that evaluates to the value <code>6</code>. Calling a function is an
|
||||
expression. Calling a macro is an expression. The block that we use to create
|
||||
new scopes, <code>{}</code>, is an expression, for example:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust">fn main() {
|
||||
let x = 5;
|
||||
|
||||
@@ -244,7 +246,7 @@ values, but we do declare their type after an arrow (<code>-></code>). In Rus
|
||||
value of the function is synonymous with the value of the final expression in
|
||||
the block of the body of a function. Here’s an example of a function that
|
||||
returns a value:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust">fn five() -> i32 {
|
||||
5
|
||||
}
|
||||
@@ -275,7 +277,7 @@ that line is the same as the following:</p>
|
||||
return value, but the body of the function is a lonely <code>5</code> with no semicolon
|
||||
because it’s an expression whose value we want to return. Let’s look at another
|
||||
example:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust">fn main() {
|
||||
let x = plus_one(5);
|
||||
|
||||
@@ -289,7 +291,7 @@ fn plus_one(x: i32) -> i32 {
|
||||
<p>Running this code will print <code>The value of x is: 6</code>. What happens if we place a
|
||||
semicolon at the end of the line containing <code>x + 1</code>, changing it from an
|
||||
expression to a statement?</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust,ignore">fn main() {
|
||||
let x = plus_one(5);
|
||||
|
||||
|
||||
@@ -83,14 +83,14 @@ line. For comments that extend beyond a single line, you’ll need to include
|
||||
// explain what’s going on.
|
||||
</code></pre>
|
||||
<p>Comments can also be placed at the end of lines containing code:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust">fn main() {
|
||||
let lucky_number = 7; // I’m feeling lucky today.
|
||||
}
|
||||
</code></pre>
|
||||
<p>But you’ll more often see them used in this format, with the comment on a
|
||||
separate line above the code it's annotating:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust">fn main() {
|
||||
// I’m feeling lucky today.
|
||||
let lucky_number = 7;
|
||||
|
||||
+26
-20
@@ -79,7 +79,7 @@ provide a condition and then state, “If this condition is met, run this block
|
||||
of code. If the condition is not met, do not run this block of code.”</p>
|
||||
<p>Create a new project called <em>branches</em> in your <em>projects</em> directory to explore
|
||||
the <code>if</code> expression. In the <em>src/main.rs</em> file, input the following:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust">fn main() {
|
||||
let number = 3;
|
||||
|
||||
@@ -123,7 +123,7 @@ condition was false
|
||||
<p>It’s also worth noting that the condition in this code <em>must</em> be a <code>bool</code>. To
|
||||
see what happens if the condition isn’t a <code>bool</code>, try running the following
|
||||
code:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust,ignore">fn main() {
|
||||
let number = 3;
|
||||
|
||||
@@ -153,7 +153,7 @@ languages such as Ruby and JavaScript. You must be explicit and always provide
|
||||
<code>if</code> with a <code>boolean</code> as its condition. If we want the <code>if</code> code block to run
|
||||
only when a number is not equal to <code>0</code>, for example, we can change the <code>if</code>
|
||||
expression to the following:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust">fn main() {
|
||||
let number = 3;
|
||||
|
||||
@@ -166,7 +166,7 @@ expression to the following:</p>
|
||||
<h4>Multiple Conditions with <code>else if</code></h4>
|
||||
<p>We can have multiple conditions by combining <code>if</code> and <code>else</code> in an <code>else if</code>
|
||||
expression. For example:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust">fn main() {
|
||||
let number = 6;
|
||||
|
||||
@@ -200,7 +200,8 @@ Rust branching construct called <code>match</code> for these cases.</p>
|
||||
<h4>Using <code>if</code> in a <code>let</code> statement</h4>
|
||||
<p>Because <code>if</code> is an expression, we can use it on the right side of a <code>let</code>
|
||||
statement, for instance in Listing 3-4:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<figure>
|
||||
<span class="filename">Filename: src/main.rs</span>
|
||||
<pre><code class="language-rust">fn main() {
|
||||
let condition = true;
|
||||
let number = if condition {
|
||||
@@ -212,9 +213,10 @@ statement, for instance in Listing 3-4:</p>
|
||||
println!("The value of number is: {}", number);
|
||||
}
|
||||
</code></pre>
|
||||
<caption>
|
||||
Listing 3-4: Assigning the result of an `if` expression to a variable
|
||||
</caption>
|
||||
<figcaption>
|
||||
<p>Listing 3-4: Assigning the result of an <code>if</code> expression to a variable</p>
|
||||
</figcaption>
|
||||
</figure>
|
||||
<p>The <code>number</code> variable will be bound to a value based on the outcome of the <code>if</code>
|
||||
expression. Run this code to see what happens:</p>
|
||||
<pre><code class="language-text">$ cargo run
|
||||
@@ -229,7 +231,7 @@ values that have the potential to be results from each arm of the <code>if</code
|
||||
the same type; in Listing 3-4, the results of both the <code>if</code> arm and the <code>else</code>
|
||||
arm were <code>i32</code> integers. But what happens if the types are mismatched, as in
|
||||
the following example?</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust,ignore">fn main() {
|
||||
let condition = true;
|
||||
|
||||
@@ -274,7 +276,7 @@ experiment with loops, let’s make a new project called <em>loops</em>.</p>
|
||||
forever or until you explicitly tell it to stop.</p>
|
||||
<p>As an example, change the <em>src/main.rs</em> file in your <em>loops</em> directory to look
|
||||
like this:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust,ignore">fn main() {
|
||||
loop {
|
||||
println!("again!");
|
||||
@@ -311,7 +313,7 @@ program, if you’d like.</p>
|
||||
for it, and it’s called a <code>while</code> loop. The following example uses <code>while</code>: the
|
||||
program loops three times, counting down each time. Then, after the loop, it
|
||||
prints another message and exits:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust">fn main() {
|
||||
let mut number = 3;
|
||||
|
||||
@@ -330,7 +332,8 @@ true, the code runs; otherwise, it exits the loop.</p>
|
||||
<h4>Looping Through a Collection with <code>for</code></h4>
|
||||
<p>You could use the <code>while</code> construct to loop over the elements of a collection,
|
||||
such as an array. For example:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<figure>
|
||||
<span class="filename">Filename: src/main.rs</span>
|
||||
<pre><code class="language-rust">fn main() {
|
||||
let a = [10, 20, 30, 40, 50];
|
||||
let mut index = 0;
|
||||
@@ -342,9 +345,10 @@ such as an array. For example:</p>
|
||||
}
|
||||
}
|
||||
</code></pre>
|
||||
<caption>
|
||||
Listing 3-5: Looping through each element of a collection using a `while` loop
|
||||
</caption>
|
||||
<figcaption>
|
||||
<p>Listing 3-5: Looping through each element of a collection using a <code>while</code> loop</p>
|
||||
</figcaption>
|
||||
</figure>
|
||||
<p>Here, the code counts up through the elements in the array. It starts at index
|
||||
<code>0</code>, and then loops until it reaches the final index in the array (that is,
|
||||
when <code>index < 5</code> is no longer true). Running this code will print out every
|
||||
@@ -367,7 +371,8 @@ perform the conditional check on every element on every iteration through the
|
||||
loop.</p>
|
||||
<p>As a more efficient alternative, you can use a <code>for</code> loop and execute some code
|
||||
for each item in a collection. A <code>for</code> loop looks like this:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<figure>
|
||||
<span class="filename">Filename: src/main.rs</span>
|
||||
<pre><code class="language-rust">fn main() {
|
||||
let a = [10, 20, 30, 40, 50];
|
||||
|
||||
@@ -376,9 +381,10 @@ for each item in a collection. A <code>for</code> loop looks like this:</p>
|
||||
}
|
||||
}
|
||||
</code></pre>
|
||||
<caption>
|
||||
Listing 3-6: Looping through each element of a collection using a `for` loop
|
||||
</caption>
|
||||
<figcaption>
|
||||
<p>Listing 3-6: Looping through each element of a collection using a <code>for</code> loop</p>
|
||||
</figcaption>
|
||||
</figure>
|
||||
<p>When we run this code, we’ll see the same output as in Listing 3-5. More
|
||||
importantly, we’ve now increased the safety of the code and eliminated the
|
||||
chance of bugs that might result from going beyond the end of the array or not
|
||||
@@ -396,7 +402,7 @@ that generates all numbers in sequence starting from one number and ending
|
||||
before another number.</p>
|
||||
<p>Here’s what the countdown would look like using a <code>for</code> loop and another method
|
||||
we’ve not yet talked about, <code>rev</code>, to reverse the range:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust">fn main() {
|
||||
for number in (1..4).rev() {
|
||||
println!("{}!", number);
|
||||
|
||||
@@ -284,11 +284,13 @@ under the covers in Figure 4-1. A <code>String</code> is made up of three parts,
|
||||
the left: a pointer to the memory that holds the contents of the string, a
|
||||
length, and a capacity. This group of data is stored on the stack. On the right
|
||||
is the memory that holds the contents, and this is on the heap.</p>
|
||||
<p><img alt="String in memory" src="img/trpl04-01.svg" class="center" style="width: 50%;" /></p>
|
||||
<caption>
|
||||
Figure 4-1: Representation in memory of a `String` holding the value `"hello"`
|
||||
bound to `s1`
|
||||
</caption>
|
||||
<figure>
|
||||
<img alt="String in memory" src="img/trpl04-01.svg" class="center" style="width: 50%;" />
|
||||
<figcaption>
|
||||
<p>Figure 4-1: Representation in memory of a <code>String</code> holding the value <code>"hello"</code>
|
||||
bound to <code>s1</code></p>
|
||||
</figcaption>
|
||||
</figure>
|
||||
<p>The length is how much memory, in bytes, the contents of the <code>String</code> is
|
||||
currently using. The capacity is the total amount of memory, in bytes, that the
|
||||
<code>String</code> has gotten from the operating system. The difference between length
|
||||
@@ -298,19 +300,23 @@ the capacity.</p>
|
||||
copy the pointer, the length, and the capacity that are on the stack. We do not
|
||||
copy the data on the heap that the <code>String</code>’s pointer refers to. In other
|
||||
words, it looks like figure 4-2.</p>
|
||||
<p><img alt="s1 and s2 pointing to the same value" src="img/trpl04-02.svg" class="center" style="width: 50%;" /></p>
|
||||
<caption>
|
||||
Figure 4-2: Representation in memory of the variable `s2` that has a copy of
|
||||
`s1`’s pointer, length and capacity
|
||||
</caption>
|
||||
<figure>
|
||||
<img alt="s1 and s2 pointing to the same value" src="img/trpl04-02.svg" class="center" style="width: 50%;" />
|
||||
<figcaption>
|
||||
<p>Figure 4-2: Representation in memory of the variable <code>s2</code> that has a copy of
|
||||
<code>s1</code>’s pointer, length and capacity</p>
|
||||
</figcaption>
|
||||
</figure>
|
||||
<p>And <em>not</em> Figure 4-3, which is what memory would look like if Rust instead
|
||||
copied the heap data as well. If Rust did this, the operation <code>s2 = s1</code> could
|
||||
potentially be very expensive if the data on the heap was large.</p>
|
||||
<p><img alt="s1 and s2 to two places" src="img/trpl04-03.svg" class="center" style="width: 50%;" /></p>
|
||||
<caption>
|
||||
Figure 4-3: Another possibility for what `s2 = s1` might do, if Rust chose to
|
||||
copy heap data as well.
|
||||
</caption>
|
||||
<figure>
|
||||
<img alt="s1 and s2 to two places" src="img/trpl04-03.svg" class="center" style="width: 50%;" />
|
||||
<figcaption>
|
||||
<p>Figure 4-3: Another possibility for what <code>s2 = s1</code> might do, if Rust chose to
|
||||
copy heap data as well.</p>
|
||||
</figcaption>
|
||||
</figure>
|
||||
<p>Earlier, we said that when a variable goes out of scope, Rust will
|
||||
automatically call the <code>drop</code> function and clean up the heap memory for that
|
||||
variable. But in figure 4-2, we see both data pointers pointing to the same
|
||||
@@ -343,10 +349,12 @@ without copying the data probably sounds like a shallow copy. But because Rust
|
||||
also invalidates the first variable, instead of calling this a shallow copy,
|
||||
it’s known as a <em>move</em>. Here we would read this by saying that <code>s1</code> was <em>moved</em>
|
||||
into <code>s2</code>. So what actually happens looks like Figure 4-4.</p>
|
||||
<p><img alt="s1 moved to s2" src="img/trpl04-04.svg" class="center" style="width: 50%;" /></p>
|
||||
<caption>
|
||||
Figure 4-4: Representation in memory after `s1` has been invalidated
|
||||
</caption>
|
||||
<figure>
|
||||
<img alt="s1 moved to s2" src="img/trpl04-04.svg" class="center" style="width: 50%;" />
|
||||
<figcaption>
|
||||
<p>Figure 4-4: Representation in memory after <code>s1</code> has been invalidated</p>
|
||||
</figcaption>
|
||||
</figure>
|
||||
<p>That solves our problem! With only <code>s2</code> valid, when it goes out of scope, it
|
||||
alone will free the memory, and we’re done.</p>
|
||||
<p>Furthermore, there’s a design choice that’s implied by this: Rust will never
|
||||
@@ -408,7 +416,7 @@ Here’s some of the types that are <code>Copy</code>:</p>
|
||||
value to a variable. Passing a variable to a function will move or copy, just
|
||||
like assignment. Here’s an example, with some annotations showing where
|
||||
variables go into and out of scope:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust">fn main() {
|
||||
let s = String::from("hello"); // s comes into scope.
|
||||
|
||||
@@ -439,7 +447,7 @@ the ownership rules prevent you from doing so.</p>
|
||||
<h3>Return Values and Scope</h3>
|
||||
<p>Returning values can also transfer ownership. Here’s an example with similar
|
||||
annotations:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust">fn main() {
|
||||
let s1 = gives_ownership(); // gives_ownership moves its return
|
||||
// value into s1.
|
||||
@@ -479,7 +487,7 @@ quite annoying that anything we pass in also needs to be passed back if we want
|
||||
to use it again, in addition to any data resulting from the body of the
|
||||
function that we might want to return as well.</p>
|
||||
<p>It is possible to return multiple values using a tuple, like this:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust">fn main() {
|
||||
let s1 = String::from("hello");
|
||||
|
||||
|
||||
@@ -75,7 +75,7 @@ into <code>calculate_length</code>.</p>
|
||||
<p>Here is how you would define and use a <code>calculate_length</code> function that takes a
|
||||
<em>reference</em> to an object as an argument instead of taking ownership of the
|
||||
argument:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust">fn main() {
|
||||
let s1 = String::from("hello");
|
||||
|
||||
@@ -94,10 +94,12 @@ function return value is gone. Next, note that we pass <code>&s1</code> into
|
||||
<code>String</code>.</p>
|
||||
<p>These <code>&</code>s are <em>references</em>, and they allow you to refer to some value without
|
||||
taking ownership of it. Figure 4-5 shows a diagram of this.</p>
|
||||
<p><img alt="&String s pointing at String s1" src="img/trpl04-05.svg" class="center" /></p>
|
||||
<caption>
|
||||
Figure 4-5: `&String s` pointing at `String s1`
|
||||
</caption>
|
||||
<figure>
|
||||
<img alt="&String s pointing at String s1" src="img/trpl04-05.svg" class="center" />
|
||||
<figcaption>
|
||||
<p>Figure 4-5: <code>&String s</code> pointing at <code>String s1</code></p>
|
||||
</figcaption>
|
||||
</figure>
|
||||
<p>Let’s take a closer look at the function call here:</p>
|
||||
<pre><code class="language-rust"># fn calculate_length(s: &String) -> usize {
|
||||
# s.len()
|
||||
@@ -125,7 +127,7 @@ something, you can borrow it from them, and when you’re done, you have to give
|
||||
it back.</p>
|
||||
<p>So what happens if we try to modify something we’re borrowing? Try this code
|
||||
out. Spoiler alert: it doesn’t work!</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust,ignore">fn main() {
|
||||
let s = String::from("hello");
|
||||
|
||||
@@ -147,7 +149,7 @@ fn change(some_string: &String) {
|
||||
to modify something we have a reference to.</p>
|
||||
<h3>Mutable References</h3>
|
||||
<p>We can fix this error with just a small tweak:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust">fn main() {
|
||||
let mut s = String::from("hello");
|
||||
|
||||
@@ -163,7 +165,7 @@ reference with <code>&mut s</code> and accept a mutable reference with <code
|
||||
<p>Mutable references have one big restriction, though: you can only have one
|
||||
mutable reference to a particular piece of data in a particular scope. This
|
||||
code will fail:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust,ignore">let mut s = String::from("hello");
|
||||
|
||||
let r1 = &mut s;
|
||||
@@ -243,7 +245,7 @@ never be dangling: if we have a reference to some data, the compiler will
|
||||
ensure that the data will not go out of scope before the reference to the data
|
||||
does.</p>
|
||||
<p>Let’s try to create a dangling reference:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust,ignore">fn main() {
|
||||
let reference_to_nothing = dangle();
|
||||
}
|
||||
|
||||
+11
-9
@@ -82,7 +82,7 @@ returned.</p>
|
||||
ownership, so this is fine. But what should we return? We don’t really have a
|
||||
way to talk about <em>part</em> of a string. We could return the index of the end of
|
||||
the word, though. Let’s try that:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust">fn first_word(s: &String) -> usize {
|
||||
let bytes = s.as_bytes();
|
||||
|
||||
@@ -127,7 +127,7 @@ only a meaningful number in the context of the <code>&String</code>. In othe
|
||||
because it’s a separate value from the <code>String</code>, there’s no guarantee that it
|
||||
will still be valid in the future. Consider this program that uses this
|
||||
<code>first_word</code> function:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust"># fn first_word(s: &String) -> usize {
|
||||
# let bytes = s.as_bytes();
|
||||
#
|
||||
@@ -181,10 +181,12 @@ slice data structure actually stores the starting position and the length of
|
||||
the slice. So in the case of <code>let world = &s[6..11];</code>, <code>world</code> would be a slice
|
||||
that contains a pointer to the 6th byte of <code>s</code> and a length value of 5.</p>
|
||||
<p>Figure 4-6 shows this in a diagram:</p>
|
||||
<p><img alt="world containing a pointer to the 6th byte of String s and a length 5" src="img/trpl04-06.svg" class="center" style="width: 50%;" /></p>
|
||||
<caption>
|
||||
Figure 4-6: String slice referring to part of a `String`
|
||||
</caption>
|
||||
<figure>
|
||||
<img alt="world containing a pointer to the 6th byte of String s and a length 5" src="img/trpl04-06.svg" class="center" style="width: 50%;" />
|
||||
<figcaption>
|
||||
<p>Figure 4-6: String slice referring to part of a <code>String</code></p>
|
||||
</figcaption>
|
||||
</figure>
|
||||
<p>With Rust’s <code>..</code> range syntax, if you want to start at the first index (zero),
|
||||
you can drop the value before the <code>..</code>. In other words, these are equal:</p>
|
||||
<pre><code class="language-rust">let s = String::from("hello");
|
||||
@@ -212,7 +214,7 @@ let slice = &s[..];
|
||||
</code></pre>
|
||||
<p>With this in mind, let’s re-write <code>first_word</code> to return a slice. The type that
|
||||
signifies “string slice” is written as <code>&str</code>:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust">fn first_word(s: &String) -> &str {
|
||||
let bytes = s.as_bytes();
|
||||
|
||||
@@ -242,7 +244,7 @@ any immediate errors. The problems would show up later, if we kept trying to
|
||||
use the first word index with an emptied string. Slices make this bug
|
||||
impossible, and let us know we have a problem with our code much sooner. Using
|
||||
the slice version of <code>first_word</code> will throw a compile time error:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust,ignore">fn main() {
|
||||
let mut s = String::from("hello world");
|
||||
|
||||
@@ -292,7 +294,7 @@ to use the same function on both <code>String</code>s and <code>&str</code>s
|
||||
<p>If we have a string slice, we can pass that as the argument directly. If we
|
||||
have a <code>String</code>, we can pass a slice of the entire <code>String</code>. This makes our API
|
||||
more general and useful without losing any functionality:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust"># fn first_word(s: &str) -> &str {
|
||||
# let bytes = s.as_bytes();
|
||||
#
|
||||
|
||||
@@ -127,8 +127,8 @@ refactor our program until we're using <code>struct</code>s instead.</p>
|
||||
<p>Let’s make a new binary project with Cargo called <em>rectangles</em> that will take
|
||||
the length and width of a rectangle specified in pixels and will calculate the
|
||||
area of the rectangle. Here’s a short program that has one way of doing just
|
||||
that to put into our project's <code>src/main.rs</code>:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
that to put into our project's <em>src/main.rs</em>:</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust">fn main() {
|
||||
let length1 = 50;
|
||||
let width1 = 30;
|
||||
@@ -160,7 +160,7 @@ expressed anywhere in our program itself. It would be more readable and more
|
||||
manageable to group length and width together.</p>
|
||||
<p>We’ve already discussed one way we might do that in Chapter 3: tuples. Here’s a
|
||||
version of our program which uses tuples:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust">fn main() {
|
||||
let rect1 = (50, 30);
|
||||
|
||||
@@ -193,7 +193,7 @@ in our code.</p>
|
||||
<h3>Refactoring with Structs: Adding More Meaning</h3>
|
||||
<p>Here is where we bring in <code>struct</code>s. We can transform our tuple into a data
|
||||
type with a name for the whole as well as names for the parts:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust">struct Rectangle {
|
||||
length: u32,
|
||||
width: u32,
|
||||
@@ -232,7 +232,7 @@ index values of <code>0</code> and <code>1</code>. This is a win for clarity.</p
|
||||
<p>It'd be nice to be able to print out an instance of our <code>Rectangle</code> while we're
|
||||
debugging our program and see the values for all its fields. Let's try using
|
||||
the <code>println!</code> macro as we have been and see what happens:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust,ignore">struct Rectangle {
|
||||
length: u32,
|
||||
width: u32,
|
||||
|
||||
+5
-3
@@ -180,6 +180,7 @@ route(IpAddrKind::V6);
|
||||
address type, at the moment we don’t have a way to store the actual <em>data</em> of
|
||||
the IP address; we only know what <em>kind</em> it is. Given that you just learned
|
||||
about structs, you might tackle this problem as in Listing 6-1:</p>
|
||||
<figure>
|
||||
<pre><code class="language-rust">enum IpAddrKind {
|
||||
V4,
|
||||
V6,
|
||||
@@ -200,9 +201,10 @@ let loopback = IpAddr {
|
||||
address: String::from("::1"),
|
||||
};
|
||||
</code></pre>
|
||||
<caption>
|
||||
Listing 6-1: Storing the data and type of an IP address using a `struct`
|
||||
</caption>
|
||||
<figcaption>
|
||||
<p>Listing 6-1: Storing the data and type of an IP address using a <code>struct</code></p>
|
||||
</figcaption>
|
||||
</figure>
|
||||
<!-- I will add wingdings here in libreoffice /Carol -->
|
||||
<p>Here, we've defined a struct <code>IpAddr</code> that has two fields: a <code>kind</code> field that
|
||||
is of type <code>IpAddrKind</code> (the enum we defined previously), and an <code>address</code>
|
||||
|
||||
+17
-11
@@ -82,6 +82,7 @@ execution.</p>
|
||||
<code>match</code>! We can write a function that can take an unknown American coin and, in
|
||||
a similar way as the counting machine, determine which coin it is and
|
||||
return its value in cents, shown here in Listing 6-2:</p>
|
||||
<figure>
|
||||
<pre><code class="language-rust">enum Coin {
|
||||
Penny,
|
||||
Nickel,
|
||||
@@ -98,10 +99,11 @@ fn value_in_cents(coin: Coin) -> i32 {
|
||||
}
|
||||
}
|
||||
</code></pre>
|
||||
<caption>
|
||||
Listing 6-2: An enum and a `match` expression that has the variants of the enum
|
||||
as its patterns.
|
||||
</caption>
|
||||
<figcaption>
|
||||
<p>Listing 6-2: An enum and a <code>match</code> expression that has the variants of the enum
|
||||
as its patterns.</p>
|
||||
</figcaption>
|
||||
</figure>
|
||||
<!--- Flagging as a place to possibly put wingding numbers -- would it work to
|
||||
put two arms in this example? I think that would illustrate the control flow
|
||||
well -->
|
||||
@@ -160,6 +162,7 @@ each of the 50 states on one side. No other coins got state designs, so only
|
||||
quarters have this extra value. We can add this information to our <code>enum</code>
|
||||
by changing the <code>Quarter</code> variant to include a <code>State</code> value stored inside it
|
||||
as we've done here in Listing 6-3:</p>
|
||||
<figure>
|
||||
<pre><code class="language-rust">#[derive(Debug)] // So we can inspect the state in a minute
|
||||
enum UsState {
|
||||
Alabama,
|
||||
@@ -174,10 +177,11 @@ enum Coin {
|
||||
Quarter(UsState),
|
||||
}
|
||||
</code></pre>
|
||||
<caption>
|
||||
Listing 6-3: A `Coin` enum where the `Quarter` variant also holds a `UsState`
|
||||
value
|
||||
</caption>
|
||||
<figcaption>
|
||||
<p>Listing 6-3: A <code>Coin</code> enum where the <code>Quarter</code> variant also holds a <code>UsState</code>
|
||||
value</p>
|
||||
</figcaption>
|
||||
</figure>
|
||||
<p>Let's imagine that a friend of ours is trying to collect all 50 state quarters.
|
||||
While we sort our loose change by coin type, we're also going to call out the
|
||||
name of the state associated with each quarter so that if it's one our friend
|
||||
@@ -228,6 +232,7 @@ the function should return the <code>None</code> value and not attempt to perfor
|
||||
operations.</p>
|
||||
<p>This function is very easy to write, thanks to <code>match</code>, and will look like
|
||||
Listing 6-4:</p>
|
||||
<figure>
|
||||
<pre><code class="language-rust">fn plus_one(x: Option<i32>) -> Option<i32> {
|
||||
match x {
|
||||
None => None,
|
||||
@@ -239,9 +244,10 @@ let five = Some(5);
|
||||
let six = plus_one(five);
|
||||
let none = plus_one(None);
|
||||
</code></pre>
|
||||
<caption>
|
||||
Listing 6-4: A function that uses a `match` expression on an `Option<i32>`
|
||||
</caption>
|
||||
<figcaption>
|
||||
<p>Listing 6-4: A function that uses a <code>match</code> expression on an <code>Option<i32></code></p>
|
||||
</figcaption>
|
||||
</figure>
|
||||
<!-- Flagging for wingding numbers -->
|
||||
<h4>Matching <code>Some(T)</code></h4>
|
||||
<p>Let's examine the first execution of <code>plus_one</code> in more detail. In the above
|
||||
|
||||
@@ -83,7 +83,7 @@ $ cd communicator
|
||||
</code></pre>
|
||||
<p>Notice that Cargo generated <em>src/lib.rs</em> instead of <em>src/main.rs</em>. Inside
|
||||
<em>src/lib.rs</em> we’ll find this:</p>
|
||||
<p>Filename: src/lib.rs</p>
|
||||
<p><span class="filename">Filename: src/lib.rs</span></p>
|
||||
<pre><code class="language-rust">#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
@@ -106,7 +106,7 @@ you have for your code.</p>
|
||||
named <code>network</code> that contains the definition of a function called <code>connect</code>.
|
||||
Every module definition in Rust starts with the <code>mod</code> keyword. Add this code to
|
||||
the beginning of the <em>lib.rs</em> file, above the test code:</p>
|
||||
<p>Filename: src/lib.rs</p>
|
||||
<p><span class="filename">Filename: src/lib.rs</span></p>
|
||||
<pre><code class="language-rust">mod network {
|
||||
fn connect() {
|
||||
}
|
||||
@@ -121,7 +121,8 @@ specify the module and use the namespace syntax <code>::</code>, like so:
|
||||
<p>We can also have multiple modules, side-by-side, in the same <em>src/lib.rs</em> file.
|
||||
For example, to have a <code>client</code> module too, that also has a function named
|
||||
<code>connect</code>, we can add:</p>
|
||||
<p>Filename: src/lib.rs</p>
|
||||
<figure>
|
||||
<span class="filename">Filename: src/lib.rs</span>
|
||||
<pre><code class="language-rust">mod network {
|
||||
fn connect() {
|
||||
}
|
||||
@@ -132,22 +133,24 @@ mod client {
|
||||
}
|
||||
}
|
||||
</code></pre>
|
||||
<caption>
|
||||
Listing 7-1: The `network` module and the `client` module defined side-by-side
|
||||
in *src/lib.rs*
|
||||
</caption>
|
||||
<figcaption>
|
||||
<p>Listing 7-1: The <code>network</code> module and the <code>client</code> module defined side-by-side
|
||||
in <em>src/lib.rs</em></p>
|
||||
</figcaption>
|
||||
</figure>
|
||||
<p>Now we have a <code>network::connect</code> function and a <code>client::connect</code> function.
|
||||
These can have completely different functionality, and the function names do
|
||||
not conflict with each other since they’re in different modules.</p>
|
||||
<p>While in this case, we’re building a library, there's nothing special about
|
||||
<code>lib.rs</code>. We could also make use of submodules in a <code>main.rs</code> as well. In fact,
|
||||
<em>lib.rs</em>. We could also make use of submodules in a <em>main.rs</em> as well. In fact,
|
||||
we can also put modules inside of modules. This can be useful as your modules
|
||||
grow to keep related functionality organized together and separate
|
||||
functionality apart. The choice of how you organize your code depends on how
|
||||
you think about the relationship between the parts of your code. For instance,
|
||||
the <code>client</code> code and its <code>connect</code> function might make more sense to users of
|
||||
our library if it was inside the <code>network</code> namespace instead, like so:</p>
|
||||
<p>Filename: src/lib.rs</p>
|
||||
<figure>
|
||||
<span class="filename">Filename: src/lib.rs</span>
|
||||
<pre><code class="language-rust">mod network {
|
||||
fn connect() {
|
||||
}
|
||||
@@ -158,15 +161,16 @@ our library if it was inside the <code>network</code> namespace instead, like so
|
||||
}
|
||||
}
|
||||
</code></pre>
|
||||
<caption>
|
||||
Listing 7-2: Moving the `client` module inside of the `network` module
|
||||
</caption>
|
||||
<figcaption>
|
||||
<p>Listing 7-2: Moving the <code>client</code> module inside of the <code>network</code> module</p>
|
||||
</figcaption>
|
||||
</figure>
|
||||
<p>In your <em>src/lib.rs</em> file, replace the existing <code>mod network</code> and <code>mod client</code>
|
||||
definitions with this one that has the <code>client</code> module as an inner module of
|
||||
<code>network</code>. Now we have the functions <code>network::connect</code> and
|
||||
<code>network::client::connect</code>: again, the two functions named <code>connect</code> don’t
|
||||
conflict with each other since they’re in different namespaces.</p>
|
||||
<p>In this way, modules form a hierarchy. The contents of <code>src/lib.rs</code> are at the
|
||||
<p>In this way, modules form a hierarchy. The contents of <em>src/lib.rs</em> are at the
|
||||
topmost level, and the submodules are at lower levels. Here’s what the
|
||||
organization of our example from Listing 7-1 looks like when thought of this
|
||||
way:</p>
|
||||
@@ -191,7 +195,8 @@ structure you would like.</p>
|
||||
that you’re used to: file systems! We can use Rust’s module system along with
|
||||
multiple files to split Rust projects up so that not everything lives in
|
||||
<em>src/lib.rs</em>. For this example, we will start with this code in <em>src/lib.rs</em>:</p>
|
||||
<p>File: src/lib.rs</p>
|
||||
<figure>
|
||||
<span class="filename">File: src/lib.rs</span>
|
||||
<pre><code class="language-rust">mod client {
|
||||
fn connect() {
|
||||
}
|
||||
@@ -207,10 +212,11 @@ mod network {
|
||||
}
|
||||
}
|
||||
</code></pre>
|
||||
<caption>
|
||||
Listing 7-3: Three modules, `client`, `network`, and `network::server` all
|
||||
defined in *src/lib.rs*
|
||||
</caption>
|
||||
<figcaption>
|
||||
<p>Listing 7-3: Three modules, <code>client</code>, <code>network</code>, and <code>network::server</code> all
|
||||
defined in <em>src/lib.rs</em></p>
|
||||
</figcaption>
|
||||
</figure>
|
||||
<p>which has this module hierarchy:</p>
|
||||
<pre><code class="language-text">communicator
|
||||
├── client
|
||||
@@ -223,7 +229,7 @@ This would be a good reason to pull each of the <code>client</code>, <code>netwo
|
||||
<code>server</code> modules out of <em>src/lib.rs</em> and into their own files. Let’s start by
|
||||
extracting the <code>client</code> module into another file. First, replace the <code>client</code>
|
||||
module code in <em>src/lib.rs</em> with the following:</p>
|
||||
<p>File: src/lib.rs</p>
|
||||
<p><span class="filename">File: src/lib.rs</span></p>
|
||||
<pre><code class="language-rust,ignore">mod client;
|
||||
|
||||
mod network {
|
||||
@@ -242,15 +248,15 @@ braces and definitions inside the <code>client</code> module and replacing them
|
||||
semicolon, we’re letting Rust know to look in another location for the code
|
||||
defined inside that module.</p>
|
||||
<p>So now we need to create the external file with that module name. Create a
|
||||
<code>client.rs</code> file in your <em>src/</em> directory, then open it up and enter the
|
||||
<em>client.rs</em> file in your <em>src/</em> directory, then open it up and enter the
|
||||
following, which is the <code>connect</code> function in the <code>client</code> module that we
|
||||
removed in the previous step:</p>
|
||||
<p>File: src/client.rs</p>
|
||||
<p><span class="filename">File: src/client.rs</span></p>
|
||||
<pre><code class="language-rust">fn connect() {
|
||||
}
|
||||
</code></pre>
|
||||
<p>Note that we don’t need a <code>mod</code> declaration in this file; that’s because we
|
||||
already declared the <code>client</code> module with <code>mod</code> in <code>src/lib.rs</code>. This file just
|
||||
already declared the <code>client</code> module with <code>mod</code> in <em>src/lib.rs</em>. This file just
|
||||
provides the <em>contents</em> of the <code>client</code> module. If we put a <code>mod client</code> here,
|
||||
we’d be giving the <code>client</code> module its own submodule named <code>client</code>!</p>
|
||||
<p>Rust only knows to look in <em>src/lib.rs</em> by default. If we want to add more
|
||||
@@ -285,15 +291,15 @@ warning: function is never used: `connect`, #[warn(dead_code)] on by default
|
||||
about those warnings for now; we’ll address them later in the chapter. The good
|
||||
news is that they’re just warnings; our project was built successfully!</p>
|
||||
<p>Let’s extract the <code>network</code> module into its own file next, using the same
|
||||
pattern. In <code>src/lib.rs</code>, delete the body of the <code>network</code> module and add a
|
||||
pattern. In <em>src/lib.rs</em>, delete the body of the <code>network</code> module and add a
|
||||
semicolon to the declaration, like so:</p>
|
||||
<p>Filename: src/lib.rs</p>
|
||||
<p><span class="filename">Filename: src/lib.rs</span></p>
|
||||
<pre><code class="language-rust,ignore">mod client;
|
||||
|
||||
mod network;
|
||||
</code></pre>
|
||||
<p>Then create a new <code>src/network.rs</code> file and enter the following:</p>
|
||||
<p>Filename: src/network.rs</p>
|
||||
<p>Then create a new <em>src/network.rs</em> file and enter the following:</p>
|
||||
<p><span class="filename">Filename: src/network.rs</span></p>
|
||||
<pre><code class="language-rust">fn connect() {
|
||||
}
|
||||
|
||||
@@ -310,19 +316,20 @@ current tactic of extracting a module into a file named after that module won’
|
||||
work. We’re going to try anyway so that we can see the error. First change
|
||||
<em>src/network.rs</em> to have <code>mod server;</code> instead of the <code>server</code> module’s
|
||||
contents:</p>
|
||||
<p>Filename: src/network.rs</p>
|
||||
<p><span class="filename">Filename: src/network.rs</span></p>
|
||||
<pre><code class="language-rust,ignore">fn connect() {
|
||||
}
|
||||
|
||||
mod server;
|
||||
</code></pre>
|
||||
<p>Then create a <code>src/server.rs</code> file and enter the contents of the <code>server</code>
|
||||
<p>Then create a <em>src/server.rs</em> file and enter the contents of the <code>server</code>
|
||||
module that we extracted:</p>
|
||||
<p>Filename: src/server.rs</p>
|
||||
<p><span class="filename">Filename: src/server.rs</span></p>
|
||||
<pre><code class="language-rust">fn connect() {
|
||||
}
|
||||
</code></pre>
|
||||
<p>When we try to <code>cargo build</code>, we’ll get this error:</p>
|
||||
<figure>
|
||||
<pre><code class="language-text">$ cargo build
|
||||
Compiling communicator v0.1.0 (file:///projects/communicator)
|
||||
error: cannot declare a new module at this location
|
||||
@@ -342,13 +349,14 @@ note: ... or maybe `use` the module `server` instead of possibly redeclaring it
|
||||
4 | mod server;
|
||||
| ^^^^^^
|
||||
</code></pre>
|
||||
<caption>
|
||||
Listing 7-4: Error when trying to extract the `server` submodule into
|
||||
*src/server.rs*
|
||||
</caption>
|
||||
<figcaption>
|
||||
<p>Listing 7-4: Error when trying to extract the <code>server</code> submodule into
|
||||
<em>src/server.rs</em></p>
|
||||
</figcaption>
|
||||
</figure>
|
||||
<p>The error says we <code>cannot declare a new module at this location</code> and is
|
||||
pointing to the <code>mod server;</code> line in <code>src/network.rs</code>. So <code>src/network.rs</code> is
|
||||
different than <code>src/lib.rs</code> somehow; let’s keep reading to understand why.</p>
|
||||
pointing to the <code>mod server;</code> line in <em>src/network.rs</em>. So <em>src/network.rs</em> is
|
||||
different than <em>src/lib.rs</em> somehow; let’s keep reading to understand why.</p>
|
||||
<p>The note in the middle of Listing 7-4 is actually pretty helpful, as it points
|
||||
out something we haven’t yet talked about doing:</p>
|
||||
<blockquote>
|
||||
@@ -388,7 +396,7 @@ same as it did when we had all the code in <em>src/lib.rs</em> in Listing 7-3:</
|
||||
also change the <em>src/network.rs</em> file into the <em>src/network/mod.rs</em> file, and
|
||||
also put the code for <code>network::server</code> in the <code>network</code> directory in
|
||||
<em>src/network/server.rs</em>, instead of just being able to extract the
|
||||
<em>network::server</em> into <em>src/server.rs</em>? The reason is that Rust wouldn’t be
|
||||
<code>network::server</code> into <em>src/server.rs</em>? The reason is that Rust wouldn’t be
|
||||
able to tell that <code>server</code> was supposed to be a submodule of <code>network</code> if the
|
||||
<em>server.rs</em> file was in the <em>src</em> directory. To make it clearer why Rust can’t
|
||||
tell, let’s consider a different example where we have this module hierarchy
|
||||
@@ -419,16 +427,16 @@ top-level <em>src/client.rs</em> is unambiguously the code that belongs to the
|
||||
<ul>
|
||||
<li>
|
||||
<p>If a module named <code>foo</code> has no submodules, you should put the declarations
|
||||
for <code>foo</code> in a file named <code>foo.rs</code>.</p>
|
||||
for <code>foo</code> in a file named <em>foo.rs</em>.</p>
|
||||
</li>
|
||||
<li>
|
||||
<p>If a module named <code>foo</code> does have submodules, you should put the declarations
|
||||
for <code>foo</code> in a file named <code>foo/mod.rs</code>.</p>
|
||||
for <code>foo</code> in a file named <em>foo/mod.rs</em>.</p>
|
||||
</li>
|
||||
<li>
|
||||
<p>The first two rules apply recursively, so that if a module named <code>foo</code> has a
|
||||
submodule named <code>bar</code> and <code>bar</code> does not have submodules, you should have the
|
||||
following files in your <code>src</code> directory:</p>
|
||||
following files in your <em>src</em> directory:</p>
|
||||
<pre><code class="language-text">├── foo
|
||||
│ ├── bar.rs (contains the declarations in `foo::bar`)
|
||||
│ └── mod.rs (contains the declarations in `foo`, including `mod bar`)
|
||||
|
||||
@@ -100,8 +100,8 @@ another project and not our own.</p>
|
||||
<p>To understand why this program invokes these warnings, let’s try using the
|
||||
<code>connect</code> library as if we were another project, calling it externally. We can
|
||||
do that by creating a binary crate in the same directory as our library crate,
|
||||
by making a <code>src/main.rs</code> file containing this code:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
by making a <em>src/main.rs</em> file containing this code:</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust,ignore">extern crate communicator;
|
||||
|
||||
fn main() {
|
||||
@@ -144,8 +144,8 @@ unused.</p>
|
||||
the declaration of the item we want to make public. We’ll focus on fixing the
|
||||
warning that tells us that <code>client::connect</code> has gone unused for now, as well
|
||||
as the “module <code>client</code> is private” error from our binary crate. Modify
|
||||
<code>src/lib.rs</code> to make the <code>client</code> module public, like so:</p>
|
||||
<p>Filename: src/lib.rs</p>
|
||||
<em>src/lib.rs</em> to make the <code>client</code> module public, like so:</p>
|
||||
<p><span class="filename">Filename: src/lib.rs</span></p>
|
||||
<pre><code class="language-rust,ignore">pub mod client;
|
||||
|
||||
mod network;
|
||||
@@ -161,7 +161,7 @@ error: function `connect` is private
|
||||
<p>Hooray! We have a different error! Yes, different error messages are a cause
|
||||
for celebration. The new error says “function <code>connect</code> is private”, so let’s
|
||||
edit <code>src/client.rs</code> to make <code>client::connect</code> public too:</p>
|
||||
<p>Filename: src/client.rs</p>
|
||||
<p><span class="filename">Filename: src/client.rs</span></p>
|
||||
<pre><code class="language-rust">pub fn connect() {
|
||||
}
|
||||
</code></pre>
|
||||
@@ -187,8 +187,8 @@ accidentally removed all places within your library where this function is
|
||||
called.</p>
|
||||
<p>In our case though, we <em>do</em> want the other two functions to be part of our
|
||||
crate’s public API, so let’s mark them as <code>pub</code> as well to try to get rid of
|
||||
the remaining warnings. Modify <code>src/network/mod.rs</code> to be:</p>
|
||||
<p>Filename: src/network/mod.rs</p>
|
||||
the remaining warnings. Modify <em>src/network/mod.rs</em> to be:</p>
|
||||
<p><span class="filename">Filename: src/network/mod.rs</span></p>
|
||||
<pre><code class="language-rust,ignore">pub fn connect() {
|
||||
}
|
||||
|
||||
@@ -213,7 +213,7 @@ within the module, but the <code>network</code> module that the function resides
|
||||
public. We’re working from the interior of the library out this time, where
|
||||
with <code>client::connect</code> we worked from the outside in. We need to change
|
||||
<code>src/lib.rs</code> to make <code>network</code> public too:</p>
|
||||
<p>Filename: src/lib.rs</p>
|
||||
<p><span class="filename">Filename: src/lib.rs</span></p>
|
||||
<pre><code class="language-rust,ignore">pub mod client;
|
||||
|
||||
pub mod network;
|
||||
@@ -236,8 +236,9 @@ child modules.</li>
|
||||
</ol>
|
||||
<h3>Privacy Examples</h3>
|
||||
<p>Let’s look at a few more examples to get some practice. Create a new libary
|
||||
project and enter the code in Listing 7-5 into your new project’s <code>src/lib.rs</code>:</p>
|
||||
<p>Filename: src/lib.rs</p>
|
||||
project and enter the code in Listing 7-5 into your new project’s <em>src/lib.rs</em>:</p>
|
||||
<figure>
|
||||
<span class="filename">Filename: src/lib.rs</span>
|
||||
<pre><code class="language-rust,ignore">mod outermost {
|
||||
pub fn middle_function() {}
|
||||
|
||||
@@ -257,6 +258,11 @@ fn try_me() {
|
||||
outermost::inside::secret_function();
|
||||
}
|
||||
</code></pre>
|
||||
<figcaption>
|
||||
<p>Listing 7-5: Examples of private and public functions, some of which are
|
||||
incorrect</p>
|
||||
</figcaption>
|
||||
</figure>
|
||||
<p>Before you try to compile this code, make a guess about which lines in <code>try_me</code>
|
||||
function will have errors. Then try compiling to see if you were right, and read
|
||||
on for discussion of the errors!</p>
|
||||
|
||||
@@ -71,7 +71,8 @@
|
||||
<p>We’ve covered how to call functions defined within a module using the module
|
||||
name as part of the call, as in the call to the <code>namespaces</code> function shown
|
||||
here in Listing 7-6.</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<figure>
|
||||
<span class="filename">Filename: src/main.rs</span>
|
||||
<pre><code class="language-rust">pub mod a {
|
||||
pub mod series {
|
||||
pub mod of {
|
||||
@@ -84,17 +85,18 @@ fn main() {
|
||||
a::series::of::namespaces();
|
||||
}
|
||||
</code></pre>
|
||||
<caption>
|
||||
Listing 7-6: Calling a function by fully specifying its enclosing module’s
|
||||
namespaces
|
||||
</caption>
|
||||
<figcaption>
|
||||
<p>Listing 7-6: Calling a function by fully specifying its enclosing module’s
|
||||
namespaces</p>
|
||||
</figcaption>
|
||||
</figure>
|
||||
<p>As you can see, referring to the fully qualified name can get quite lengthy.
|
||||
Luckily, Rust has a keyword to make these calls more concise.</p>
|
||||
<h3>Concise Imports with <code>use</code></h3>
|
||||
<p>Rust’s <code>use</code> keyword works to shorten lengthy function calls by bringing the
|
||||
modules of the function you want to call into a scope. Here’s an example of
|
||||
bringing the <code>a::series::of</code> namespace into a binary crate’s root scope:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust">pub mod a {
|
||||
pub mod series {
|
||||
pub mod of {
|
||||
@@ -174,8 +176,8 @@ might also pull in more things than you expected and cause naming conflicts.</p>
|
||||
<h3>Using <code>super</code> to Access a Parent Module</h3>
|
||||
<p>As you now know, when you create a library crate, Cargo makes a <code>tests</code> module
|
||||
for you. Let’s go into more detail about that now. In your <code>communicator</code>
|
||||
project, open <code>src/lib.rs</code>.</p>
|
||||
<p>Filename: src/lib.rs</p>
|
||||
project, open <em>src/lib.rs</em>.</p>
|
||||
<p><span class="filename">Filename: src/lib.rs</span></p>
|
||||
<pre><code class="language-rust,ignore">pub mod client;
|
||||
|
||||
pub mod network;
|
||||
@@ -201,7 +203,7 @@ looks like this:</p>
|
||||
<p>Tests are for exercising the code within our library, so let’s try to call
|
||||
our <code>client::connect</code> function from this <code>it_works</code> function, even though
|
||||
we’re not going to be checking any functionality right now:</p>
|
||||
<p>Filename: src/lib.rs</p>
|
||||
<p><span class="filename">Filename: src/lib.rs</span></p>
|
||||
<pre><code class="language-rust">#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
@@ -254,7 +256,7 @@ functionality changes the path you give to <code>use</code> so that it is relati
|
||||
parent module instead of to the root module.</p>
|
||||
<p>For these reasons, in the <code>tests</code> module especially, <code>use super::something</code> is
|
||||
usually the way to go. So now our test looks like this:</p>
|
||||
<p>Filename: src/lib.rs</p>
|
||||
<p><span class="filename">Filename: src/lib.rs</span></p>
|
||||
<pre><code class="language-rust">#[cfg(test)]
|
||||
mod tests {
|
||||
use super::client;
|
||||
|
||||
@@ -84,10 +84,11 @@ without cleaning up. Memory that the program was using will need to be cleaned
|
||||
up by the operating system. If you're in a situation where you need to make
|
||||
the resulting binary as small as possible, you can switch from unwinding on
|
||||
panic to aborting on panic by adding <code>panic = 'abort'</code> to the appropriate
|
||||
<code>[profile]</code> sections in your <code>Cargo.toml</code>.</p>
|
||||
<code>[profile]</code> sections in your <em>Cargo.toml</em>.</p>
|
||||
</blockquote>
|
||||
<!-- PROD: END BOX -->
|
||||
<p>Let's try out calling <code>panic!()</code> with a simple program:</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust,should_panic">fn main() {
|
||||
panic!("crash and burn");
|
||||
}
|
||||
@@ -103,10 +104,11 @@ error: Process didn't exit successfully: `target/debug/panic` (exit code: 101)
|
||||
</code></pre>
|
||||
<p>There are three lines of error message here. The first line shows our panic
|
||||
message and the place in our source code where the panic occurred:
|
||||
<code>src/main.rs</code>, line two.</p>
|
||||
<em>src/main.rs</em>, line two.</p>
|
||||
<p>But that only shows us the exact line that called <code>panic!</code>. That's not always
|
||||
useful. Let's look at another example to see what it's like when a <code>panic!</code>
|
||||
call comes from code we call instead of from our code directly:</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust,should_panic">fn main() {
|
||||
let v = vec![1, 2, 3];
|
||||
|
||||
@@ -136,13 +138,14 @@ thread 'main' panicked at 'index out of bounds: the len is 3 but the index is
|
||||
note: Run with `RUST_BACKTRACE=1` for a backtrace.
|
||||
error: Process didn't exit successfully: `target/debug/panic` (exit code: 101)
|
||||
</code></pre>
|
||||
<p>This points at a file we didn't write, <code>../src/libcollections/vec.rs</code>. That's
|
||||
<p>This points at a file we didn't write, <em>../src/libcollections/vec.rs</em>. That's
|
||||
the implementation of <code>Vec<T></code> in the standard library. While it's easy to see
|
||||
in this short program where the error was, it would be nicer if we could have
|
||||
Rust tell us what line in our program caused the error.</p>
|
||||
<p>That's what the next line, the <code>note</code> is about. If we set the <code>RUST_BACKTRACE</code>
|
||||
environment variable, we'll get a backtrace of exactly how the error happend.
|
||||
Let's try that. Listing 9-1 shows the output:</p>
|
||||
<figure>
|
||||
<pre><code class="language-text">$ RUST_BACKTRACE=1 cargo run
|
||||
Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs
|
||||
Running `target/debug/panic`
|
||||
@@ -175,12 +178,13 @@ core..ops..Index<usize>>::index::hb9f10d3dadbe8101
|
||||
17: 0x0 - <unknown>
|
||||
error: Process didn't exit successfully: `target/debug/panic` (exit code: 101)
|
||||
</code></pre>
|
||||
<caption>
|
||||
Listing 9-1: The backtrace generated by a call to `panic!` displayed when
|
||||
the environment variable `RUST_BACKTRACE` is set
|
||||
</caption>
|
||||
<figcaption>
|
||||
<p>Listing 9-1: The backtrace generated by a call to <code>panic!</code> displayed when
|
||||
the environment variable <code>RUST_BACKTRACE</code> is set</p>
|
||||
</figcaption>
|
||||
</figure>
|
||||
<p>That's a lot of output! Line 11 of the backtrace points to the line in our
|
||||
project causing the problem: <code>src/main.rs</code> line four. The key to reading the
|
||||
project causing the problem: <em>src/main.rs</em> line four. The key to reading the
|
||||
backtrace is to start from the top and read until we see files that we wrote:
|
||||
that's where the problem originated. If we didn't want our program to panic
|
||||
here, this line is where we would start investigating in order to figure out
|
||||
|
||||
@@ -89,21 +89,26 @@ in more detail in Chapter 10. What you need to know for right now is that the
|
||||
<code>T</code> that is what we want to return in the success case, and any type <code>E</code> that
|
||||
is what we want to return in the error case.</p>
|
||||
<p>Listing 9-2 shows an example of something that might fail: opening a file.</p>
|
||||
<figure>
|
||||
<span class="filename">Filename: src/main.rs</span>
|
||||
<pre><code class="language-rust">use std::fs::File;
|
||||
|
||||
fn main() {
|
||||
let f = File::open("hello.txt");
|
||||
}
|
||||
</code></pre>
|
||||
<caption>
|
||||
Listing 9-2: Opening a file
|
||||
</caption>
|
||||
<figcaption>
|
||||
<p>Listing 9-2: Opening a file</p>
|
||||
</figcaption>
|
||||
</figure>
|
||||
<p>The type of <code>f</code> in this example is a <code>Result</code>, because there are many ways in
|
||||
which opening a file can fail. For example, unless we created <code>hello.txt</code>, this
|
||||
file does not yet exist. Before we can do anything with our <code>File</code>, we need to
|
||||
extract it out of the result. Listing 9-3 shows one way to handle the <code>Result</code>
|
||||
with a basic tool: the <code>match</code> expression that we learned about in Chapter 6.</p>
|
||||
<!-- I'll ghost everything except the match statement lines in the libreoffice file /Carol -->
|
||||
<figure>
|
||||
<span class="filename">Filename: src/main.rs</span>
|
||||
<pre><code class="language-rust,should_panic">use std::fs::File;
|
||||
|
||||
fn main() {
|
||||
@@ -116,9 +121,11 @@ error),
|
||||
};
|
||||
}
|
||||
</code></pre>
|
||||
<caption>
|
||||
Listing 9-3: Using a `match` expression to handle the `Result` variants we might have
|
||||
</caption>
|
||||
<figcaption>
|
||||
<p>Listing 9-3: Using a <code>match</code> expression to handle the <code>Result</code> variants we
|
||||
might have</p>
|
||||
</figcaption>
|
||||
</figure>
|
||||
<p>If we see an <code>Ok</code>, we can return the inner <code>file</code> out of the <code>Ok</code> variant. If
|
||||
we see <code>Err</code>, we have to decide what to do with it. The simplest thing is to
|
||||
turn our error into a <code>panic!</code> instead, by calling the macro. And since we
|
||||
@@ -138,6 +145,8 @@ which is a struct provided by the standard library. This struct has a method
|
||||
<code>kind</code> that we can call to get an <a href="../std/io/enum.ErrorKind.html"><code>io::ErrorKind</code></a><!-- ignore -->
|
||||
value that we can use to handle different causes of an <code>Err</code> returned from
|
||||
<code>File::open</code> differently as in Listing 9-4:</p>
|
||||
<figure>
|
||||
<span class="filename">Filename: src/main.rs</span>
|
||||
<pre><code class="language-rust,ignore">use std::fs::File;
|
||||
use std::io::ErrorKind;
|
||||
|
||||
@@ -157,9 +166,10 @@ error),
|
||||
};
|
||||
}
|
||||
</code></pre>
|
||||
<caption>
|
||||
Listing 9-4: Handling different kinds of errors in different ways
|
||||
</caption>
|
||||
<figcaption>
|
||||
<p>Listing 9-4: Handling different kinds of errors in different ways</p>
|
||||
</figcaption>
|
||||
</figure>
|
||||
<!-- I will add ghosting and wingdings here in libreoffice /Carol -->
|
||||
<p>This example uses a <em>match guard</em> with the second arm's pattern to add a
|
||||
condition that further refines the pattern. The <code>ref</code> in the pattern is needed
|
||||
@@ -174,6 +184,7 @@ communicate intent well. The <code>Result<T, E></code> type has many helpe
|
||||
defined on it to do various things. "Panic on an error result" is one of those
|
||||
methods, and it's called <code>unwrap()</code>:</p>
|
||||
<!-- I'll ghost everything except `unwrap()` in the libreoffice file /Carol -->
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust,should_panic">use std::fs::File;
|
||||
|
||||
fn main() {
|
||||
@@ -187,6 +198,7 @@ the error message: <code>expect()</code>. Using <code>expect()</code> instead of
|
||||
providing good error messages can convey your intent and make tracking down the
|
||||
source of a panic easier. <code>expect()</code> looks like this:</p>
|
||||
<!-- I'll ghost everything except `expect()` in the libreoffice file /Carol -->
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust,should_panic">use std::fs::File;
|
||||
|
||||
fn main() {
|
||||
@@ -227,6 +239,7 @@ you can return the error to the calling function. For example, Listing 9-5
|
||||
shows a function that reads a username from a file. If the file doesn't exist
|
||||
or can't be read, this function will return those errors to the code that
|
||||
called this function:</p>
|
||||
<figure>
|
||||
<pre><code class="language-rust"># use std::fs::File;
|
||||
# use std::io;
|
||||
# use std::io::Read;
|
||||
@@ -247,9 +260,10 @@ fn read_username_from_file() -> Result<String, io::Error> {
|
||||
}
|
||||
}
|
||||
</code></pre>
|
||||
<caption>
|
||||
Listing 9-5: A function that returns errors to the calling code using `match`
|
||||
</caption>
|
||||
<figcaption>
|
||||
<p>Listing 9-5: A function that returns errors to the calling code using <code>match</code></p>
|
||||
</figcaption>
|
||||
</figure>
|
||||
<p>Since the <code>Result</code> type has two type parameters, we need to include them both
|
||||
in our function signature. In this case, <code>File::open</code> and <code>read_to_string</code>
|
||||
return <code>std::io::Error</code> as the value inside the <code>Err</code> variant, so we will also
|
||||
@@ -265,6 +279,7 @@ as in Listing 9-6, and it would have the same functionality as the <code>match</
|
||||
expressions:</p>
|
||||
<!-- I'll ghost everything except the calls to `try!` in the libreoffice file
|
||||
/Carol -->
|
||||
<figure>
|
||||
<pre><code class="language-rust"># use std::fs::File;
|
||||
# use std::io;
|
||||
# use std::io::Read;
|
||||
@@ -278,10 +293,12 @@ fn read_username_from_file() -> Result<String, io::Error> {
|
||||
Ok(s)
|
||||
}
|
||||
</code></pre>
|
||||
<caption>
|
||||
Listing 9-6: A function that returns errors to the calling code using `try!`
|
||||
</caption>
|
||||
<figcaption>
|
||||
<p>Listing 9-6: A function that returns errors to the calling code using <code>try!</code></p>
|
||||
</figcaption>
|
||||
</figure>
|
||||
<p>Or as in Listing 9-7, which uses the question mark operator:</p>
|
||||
<figure>
|
||||
<pre><code class="language-rust"># fn main() {}
|
||||
# use std::fs::File;
|
||||
# use std::io;
|
||||
@@ -294,9 +311,10 @@ fn read_username_from_file() -> Result<String, io::Error> {
|
||||
Ok(s)
|
||||
}
|
||||
</code></pre>
|
||||
<caption>
|
||||
Listing 9-7: A function that returns errors to the calling code using `?`
|
||||
</caption>
|
||||
<figcaption>
|
||||
<p>Listing 9-7: A function that returns errors to the calling code using <code>?</code></p>
|
||||
</figcaption>
|
||||
</figure>
|
||||
<p>The <code>?</code> operator at the end of the <code>open</code> call does the same thing as the
|
||||
example that uses <code>match</code> and the example that uses the <code>try!</code> macro: It will
|
||||
return the value inside an <code>Ok</code> to the binding <code>f</code>, but will return early out
|
||||
@@ -324,6 +342,7 @@ used in functions that return a <code>Result</code>, since they expand to the sa
|
||||
expression we saw above that had a potential early return of an <code>Err</code> value.
|
||||
Let's look at what happens if we try to use <code>try!</code> in the <code>main</code> function,
|
||||
which you'll recall has a return type of <code>()</code>:</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust,ignore"># use std::fs::File;
|
||||
fn main() {
|
||||
let f = try!(File::open("hello.txt"));
|
||||
|
||||
@@ -163,6 +163,7 @@ in the type's constructor. Then our functions can use the type with the
|
||||
confidence that we have values that meet our requirements. Listing 9-8 shows
|
||||
one way to define a <code>Guess</code> type that will only create an instance of <code>Guess</code>
|
||||
if the <code>new</code> function gets a value between 1 and 100:</p>
|
||||
<figure>
|
||||
<pre><code class="language-rust">struct Guess {
|
||||
value: u32,
|
||||
}
|
||||
@@ -183,9 +184,10 @@ impl Guess {
|
||||
}
|
||||
}
|
||||
</code></pre>
|
||||
<caption>
|
||||
Listing 9-8: A `Guess` type that will only hold values between 1 and 100
|
||||
</caption>
|
||||
<figcaption>
|
||||
<p>Listing 9-8: A <code>Guess</code> type that will only hold values between 1 and 100</p>
|
||||
</figcaption>
|
||||
</figure>
|
||||
<p>If code calling <code>Guess::new</code> passed in a value that was not between 1 and 100,
|
||||
that would be a violation of the contract that <code>Guess::new</code> is relying on. This
|
||||
function needs to signal to the calling code that it has a bug somewhere
|
||||
|
||||
@@ -84,7 +84,8 @@ in this chapter.</p>
|
||||
<p>Let's first go through a technique for dealing with duplication that you're
|
||||
probably familiar with: extracting a function. Consider a small program that
|
||||
finds the largest number in a list, shown in Listing 10-1:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<figure>
|
||||
<span class="filename">Filename: src/main.rs</span>
|
||||
<pre><code class="language-rust">fn main() {
|
||||
let numbers = vec![34, 50, 25, 100, 65];
|
||||
|
||||
@@ -99,13 +100,14 @@ finds the largest number in a list, shown in Listing 10-1:</p>
|
||||
println!("The largest number is {}", largest);
|
||||
}
|
||||
</code></pre>
|
||||
<caption>
|
||||
Listing 10-1: Code to find the largest number in a list of numbers
|
||||
</caption>
|
||||
<figcaption>
|
||||
<p>Listing 10-1: Code to find the largest number in a list of numbers</p>
|
||||
</figcaption>
|
||||
</figure>
|
||||
<p>If we needed to find the largest number in two different lists of numbers, we
|
||||
could duplicate the code in Listing 10-1 and have the same logic exist in two
|
||||
places in the program:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust">fn main() {
|
||||
let numbers = vec![34, 50, 25, 100, 65];
|
||||
|
||||
@@ -139,7 +141,7 @@ abstraction we'll use is a function. Here's a program where we've extracted the
|
||||
code in Listing 10-1 that finds the largest number into a function named
|
||||
<code>largest</code>. This program can find the largest number in two different lists of
|
||||
numbers, but the code from Listing 10-1 only exists in one spot:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust">fn largest(numbers: Vec<i32>) {
|
||||
let mut largest = numbers[0];
|
||||
|
||||
|
||||
+23
-17
@@ -91,7 +91,7 @@ we'll remove the duplication by extracting a generic data type instead of
|
||||
extracting a function, but the mechanics of doing the extraction will be
|
||||
similar. First, let's consider an <code>Option</code> enum with a <code>Some</code> variant that can
|
||||
only hold an <code>i32</code>. We'll call this enum <code>OptionalNumber</code>:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust">enum OptionalNumber {
|
||||
Some(i32),
|
||||
None,
|
||||
@@ -106,7 +106,7 @@ fn main() {
|
||||
would have to duplicate code to define a separate <code>Option</code> enum type for each
|
||||
type we wanted to be able to hold in the <code>Some</code> variants. For example, here is
|
||||
how we could define and use <code>OptionalFloatingPointNumber</code>:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust">enum OptionalFloatingPointNumber {
|
||||
Some(f64),
|
||||
None,
|
||||
@@ -197,7 +197,7 @@ is the compiler will see that we've used two kinds of <code>Option<T></cod
|
||||
definition of <code>Option<T></code> into <code>Option_i32</code> and <code>Option_f64</code>, thereby replacing
|
||||
the generic definition with the specific ones. The more specific version looks
|
||||
like the duplicated code we started with at the beginning of this section:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust">enum Option_i32 {
|
||||
Some(i32),
|
||||
None,
|
||||
@@ -223,7 +223,8 @@ well in order to define structs that have a generic type parameter in one or
|
||||
more of their fields. Generic structs also get monomorphized into specialized
|
||||
types at compile time. Listing 10-2 shows the definition and use of a <code>Point</code>
|
||||
struct that could hold <code>x</code> and <code>y</code> coordinate values that are any type:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<figure>
|
||||
<span class="filename">Filename: src/main.rs</span>
|
||||
<pre><code class="language-rust">struct Point<T> {
|
||||
x: T,
|
||||
y: T,
|
||||
@@ -234,9 +235,10 @@ fn main() {
|
||||
let float = Point { x: 1.0, y: 4.0 };
|
||||
}
|
||||
</code></pre>
|
||||
<caption>
|
||||
Listing 10-2: A `Point` struct that holds `x` and `y` values of type `T`
|
||||
</caption>
|
||||
<figcaption>
|
||||
<p>Listing 10-2: A <code>Point</code> struct that holds <code>x</code> and <code>y</code> values of type <code>T</code></p>
|
||||
</figcaption>
|
||||
</figure>
|
||||
<p>The syntax is the same with structs: add a <code><T></code> after the name of the struct,
|
||||
then use <code>T</code> in the definition where you want to use that generic type instead
|
||||
of a specific type.</p>
|
||||
@@ -261,7 +263,8 @@ type of <code>x</code>:</p>
|
||||
declare multiple type parameters within the angle brackets, separated by a
|
||||
comma. Listing 10-3 shows how to define a <code>Point</code> that can have different types
|
||||
for <code>x</code> and <code>y</code>:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<figure>
|
||||
<span class="filename">Filename: src/main.rs</span>
|
||||
<pre><code class="language-rust">struct Point<X, Y> {
|
||||
x: X,
|
||||
y: Y,
|
||||
@@ -273,10 +276,11 @@ fn main() {
|
||||
let p = Point { x: 5, y: 20.0 };
|
||||
}
|
||||
</code></pre>
|
||||
<caption>
|
||||
Listing 10-2: A `Point` struct that holds an `x` value of type `X` and a `y`
|
||||
value of type `Y`
|
||||
</caption>
|
||||
<figcaption>
|
||||
<p>Listing 10-3: A <code>Point</code> struct that holds an <code>x</code> value of type <code>X</code> and a <code>y</code>
|
||||
value of type <code>Y</code></p>
|
||||
</figcaption>
|
||||
</figure>
|
||||
<p>Now <code>x</code> will have the type of <code>X</code>, and <code>y</code> will have the type of <code>Y</code>, and we
|
||||
can instantiate a <code>Point</code> with an <code>i32</code> for <code>x</code> and an <code>f64</code> for <code>y</code>.</p>
|
||||
<p>We can make <code>enum</code>s with multiple type parameters as well. Recall the enum
|
||||
@@ -322,17 +326,19 @@ one:</p>
|
||||
</code></pre>
|
||||
<p>There's one problem though. We've got some function <em>definitions</em> that work,
|
||||
but if we try to use <code>value</code> in code in the function body, we'll get an
|
||||
error. For example, the function definition in Listing 10-3 tries to print out
|
||||
error. For example, the function definition in Listing 10-4 tries to print out
|
||||
<code>value</code> in its body:</p>
|
||||
<p>Filename: src/lib.rs</p>
|
||||
<figure>
|
||||
<span class="filename">Filename: src/lib.rs</span>
|
||||
<pre><code class="language-rust,ignore">fn show_anything<T>(value: T) {
|
||||
println!("I have something to show you!");
|
||||
println!("It's: {}", value);
|
||||
}
|
||||
</code></pre>
|
||||
<caption>
|
||||
Listing 10-3: A `show_anything` function definition that does not yet compile
|
||||
</caption>
|
||||
<figcaption>
|
||||
<p>Listing 10-4: A <code>show_anything</code> function definition that does not yet compile</p>
|
||||
</figcaption>
|
||||
</figure>
|
||||
<p>Compiling this definition results in an error:</p>
|
||||
<pre><code class="language-text"> error[E0277]: the trait bound `T: std::fmt::Display` is not satisfied
|
||||
--> <anon>:3:37
|
||||
|
||||
+38
-30
@@ -79,16 +79,18 @@ methods defined on it that allow us to print a value of that type. This is
|
||||
powerful because we can still leave our definitions generic to allow use of
|
||||
many different types, but we can constrain the type at compile-time to types
|
||||
that have the behavior we need to be able to use.</p>
|
||||
<p>Here's an example definition of a trait named <code>Printable</code> that has a method
|
||||
named <code>print</code>:</p>
|
||||
<p>Filename: src/lib.rs</p>
|
||||
<p>Listing 10-5 has an example definition of a trait named <code>Printable</code> with a
|
||||
method named <code>print</code>:</p>
|
||||
<figure>
|
||||
<span class="filename">Filename: src/lib.rs</span>
|
||||
<pre><code class="language-rust">trait Printable {
|
||||
fn print(&self);
|
||||
}
|
||||
</code></pre>
|
||||
<caption>
|
||||
Listing 10-4: A `Printable` trait definition with one method, `print`
|
||||
</caption>
|
||||
<figcaption>
|
||||
<p>Listing 10-5: A <code>Printable</code> trait definition with one method, <code>print</code></p>
|
||||
</figcaption>
|
||||
</figure>
|
||||
<p>We declare a trait with the <code>trait</code> keyword, then the trait's name. In this
|
||||
case, our trait will describe types which can be printed. Inside of curly
|
||||
braces, we declare a method signature, but instead of providing an
|
||||
@@ -97,10 +99,11 @@ trait can have multiple methods in its body, with the method signatures listend
|
||||
<p>Implementing a trait for a particular type looks similar to implementing
|
||||
methods on a type since it's also done with the <code>impl</code> keyword, but we specify
|
||||
the trait name as well. Inside the <code>impl</code> block, we specify definitions for the
|
||||
trait's methods in the context of the specific type. Listing 10-5 has an
|
||||
example of implementing the <code>Printable</code> trait from Listing 10-4 (that only has
|
||||
trait's methods in the context of the specific type. Listing 10-6 has an
|
||||
example of implementing the <code>Printable</code> trait from Listing 10-5 (that only has
|
||||
the <code>print</code> method) for a <code>Temperature</code> enum:</p>
|
||||
<p>Filename: src/lib.rs</p>
|
||||
<figure>
|
||||
<span class="filename">Filename: src/lib.rs</span>
|
||||
<pre><code class="language-rust"># trait Printable {
|
||||
# fn print(&self);
|
||||
# }
|
||||
@@ -119,13 +122,14 @@ impl Printable for Temperature {
|
||||
}
|
||||
}
|
||||
</code></pre>
|
||||
<caption>
|
||||
Listing 10-5: Implementing the `Printable` trait on a `Temperature` enum
|
||||
</caption>
|
||||
<figcaption>
|
||||
<p>Listing 10-6: Implementing the <code>Printable</code> trait on a <code>Temperature</code> enum</p>
|
||||
</figcaption>
|
||||
</figure>
|
||||
<p>In the same way <code>impl</code> lets us define methods, we've used it to define methods
|
||||
that pertain to our trait. We can call methods that our trait has defined just
|
||||
like we can call other methods:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust"># trait Printable {
|
||||
# fn print(&self);
|
||||
# }
|
||||
@@ -162,14 +166,15 @@ brought the trait we wanted into our current scope with <code>use</code>.</p>
|
||||
type gives Rust more information than just defining methods on a type directly.
|
||||
The information Rust gets is that the type that implements the trait can be
|
||||
used in places where the code specifies that it needs some type that implements
|
||||
a trait. To illustrate this, Listing 10-6 has a <code>print_anything</code> function
|
||||
definition. This is similar to the <code>show_anything</code> function from Listing 10-3,
|
||||
a trait. To illustrate this, Listing 10-7 has a <code>print_anything</code> function
|
||||
definition. This is similar to the <code>show_anything</code> function from Listing 10-4,
|
||||
but this function has a <em>trait bound</em> on the generic type <code>T</code> and uses the
|
||||
<code>print</code> function from the trait. A trait bound constrains the generic type to
|
||||
be any type that implements the trait specified, instead of any type at all.
|
||||
With the trait bound, we're then allowed to use the trait method <code>print</code> in the
|
||||
function body:</p>
|
||||
<p>Filename: src/lib.rs</p>
|
||||
<figure>
|
||||
<span class="filename">Filename: src/lib.rs</figure>
|
||||
<pre><code class="language-rust"># trait Printable {
|
||||
# fn print(&self);
|
||||
# }
|
||||
@@ -179,10 +184,11 @@ fn print_anything<T: Printable>(value: T) {
|
||||
value.print();
|
||||
}
|
||||
</code></pre>
|
||||
<caption>
|
||||
Listing 10-6: A `print_anything` function that uses the trait bound `Printable`
|
||||
on type `T`
|
||||
</caption>
|
||||
<figcaption>
|
||||
<p>Listing 10-7: A <code>print_anything</code> function that uses the trait bound <code>Printable</code>
|
||||
on type <code>T</code></p>
|
||||
</figcaption>
|
||||
</figure>
|
||||
<p>Trait bounds are specified in the type name declarations within the angle
|
||||
brackets. After the name of the type that you want to apply the bound to, add a
|
||||
colon (<code>:</code>) and then specify the name of the trait. This function now specifies
|
||||
@@ -190,10 +196,10 @@ that it takes a <code>value</code> parameter that can be of any type, as long as
|
||||
implements the trait <code>Printable</code>. We need to specify the <code>Printable</code> trait in
|
||||
the type name declarations because we want to be able to call the <code>print</code>
|
||||
method that is part of the <code>Printable</code> trait.</p>
|
||||
<p>Now we are able to call the <code>print_anything</code> function from Listing 10-6 and
|
||||
<p>Now we are able to call the <code>print_anything</code> function from Listing 10-7 and
|
||||
pass it a <code>Temperature</code> instance as the <code>value</code> parameter, since we implemented
|
||||
the trait <code>Printable</code> on <code>Temperature</code> in Listing 10-5:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
the trait <code>Printable</code> on <code>Temperature</code> in Listing 10-6:</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust"># trait Printable {
|
||||
# fn print(&self);
|
||||
# }
|
||||
@@ -241,10 +247,11 @@ standard library, and they're used for many, many different things. For
|
||||
example, our <code>Printable</code> trait is similar to one of those traits, <code>Display</code>.
|
||||
And in fact, that's how <code>println!</code> decides how to format things with <code>{}</code>. The
|
||||
<code>Display</code> trait has a <code>fmt</code> method that determines how to format something.</p>
|
||||
<p>Listing 10-7 shows our original example from Listing 10-3, but this time using
|
||||
<p>Listing 10-8 shows our original example from Listing 10-3, but this time using
|
||||
the standard library's <code>Display</code> trait in the trait bound on the generic type
|
||||
in the <code>show_anything</code> function:</p>
|
||||
<p>Filename: src/lib.rs</p>
|
||||
<figure>
|
||||
<span class="filename">Filename: src/lib.rs</span>
|
||||
<pre><code class="language-rust">use std::fmt::Display;
|
||||
|
||||
fn show_anything<T: Display>(value: T) {
|
||||
@@ -252,9 +259,10 @@ fn show_anything<T: Display>(value: T) {
|
||||
println!("It's: {}", value);
|
||||
}
|
||||
</code></pre>
|
||||
<caption>
|
||||
Listing 10-7: The `show_anything` function with trait bounds
|
||||
</caption>
|
||||
<figcaption>
|
||||
<p>Listing 10-8: The <code>show_anything</code> function with trait bounds</p>
|
||||
</figcaption>
|
||||
</figure>
|
||||
<p>Now that this function specifies that <code>T</code> can be any type as long as that type
|
||||
implements the <code>Display</code> trait, this code will compile.</p>
|
||||
<h3>Multiple Trait Bounds and <code>where</code> Syntax</h3>
|
||||
@@ -276,8 +284,8 @@ Listing 10-3 referred to it:</p>
|
||||
</code></pre>
|
||||
<p>The <code>where</code> syntax moves the trait bounds after the function arguments list.
|
||||
This definition of <code>show_anything</code> means the exact same thing as the definition
|
||||
in Listing 10-7, just said a different way:</p>
|
||||
<p>Filename: src/lib.rs</p>
|
||||
in Listing 10-8, just said a different way:</p>
|
||||
<p><span class="filename">Filename: src/lib.rs</span></p>
|
||||
<pre><code class="language-rust">use std::fmt::Display;
|
||||
|
||||
fn show_anything<T>(value: T) where T: Display {
|
||||
|
||||
@@ -110,6 +110,8 @@ scope. The outer scope declares a variable named <code>r</code> with no initial
|
||||
the inner scope declares a variable named <code>x</code> with the initial value of 5.
|
||||
Inside the inner scope, we attempt to set the value of <code>r</code> to a reference to
|
||||
<code>x</code>. Then the inner scope ends and we attempt to print out the value in <code>r</code>:</p>
|
||||
<figure>
|
||||
<span class="filename">Filename: src/lib.rs</span>
|
||||
<pre><code class="language-rust,ignore">{
|
||||
let r;
|
||||
|
||||
@@ -121,9 +123,10 @@ Inside the inner scope, we attempt to set the value of <code>r</code> to a refer
|
||||
println!("r: {}", r);
|
||||
}
|
||||
</code></pre>
|
||||
<caption>
|
||||
Listing 10-8: An attempt to use a reference whose value has gone out of scope
|
||||
</caption>
|
||||
<figcaption>
|
||||
<p>Listing 10-8: An attempt to use a reference whose value has gone out of scope</p>
|
||||
</figcaption>
|
||||
</figure>
|
||||
<p>If we compile this code, we get an error:</p>
|
||||
<pre><code class="language-text"> error: `x` does not live long enough
|
||||
--> <anon>:6:10
|
||||
@@ -229,7 +232,8 @@ return the longest of two string slices. The way we want to be able to call
|
||||
this function is by passing two string slices, and we want to get back a string
|
||||
slice. The code in Listing 10-9 should print <code>The longest string is abcd</code> once
|
||||
we've implemented the <code>longest</code> function:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<figure>
|
||||
<span class="filename">Filename: src/main.rs</span>
|
||||
<pre><code class="language-rust"># fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
|
||||
# if x.len() > y.len() {
|
||||
# x
|
||||
@@ -246,10 +250,11 @@ fn main() {
|
||||
println!("The longest string is {}", c);
|
||||
}
|
||||
</code></pre>
|
||||
<caption>
|
||||
Listing 10-9: A `main` function that demonstrates how we'd like to use the
|
||||
`longest` function
|
||||
</caption>
|
||||
<figcaption>
|
||||
<p>Listing 10-9: A <code>main</code> function that demonstrates how we'd like to use the
|
||||
<code>longest</code> function</p>
|
||||
</figcaption>
|
||||
</figure>
|
||||
<p>Note that we want the function to take string slices because we don't want the
|
||||
<code>longest</code> function to take ownership of its arguments, and we want the function
|
||||
to be able to accept slices of a <code>String</code> (like <code>a</code>) is as well as string
|
||||
@@ -257,6 +262,7 @@ literals (<code>b</code>). Refer back to the "String Slices as Arguments&qu
|
||||
Chapter 4 for more discussion about why these are the arguments we want.</p>
|
||||
<p>Here's the start of an implementation of the <code>longest</code> function that won't
|
||||
compile yet:</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust,ignore">fn longest(x: &str, y: &str) -> &str {
|
||||
if x.len() > y.len() {
|
||||
x
|
||||
@@ -280,7 +286,7 @@ know either, since in the <code>if</code> block in the body of this function ret
|
||||
reference to <code>x</code> and the <code>else</code> block returns a reference to <code>y</code>! The way to
|
||||
specify the lifetime parameters in this case is to have the same lifetime for
|
||||
all of the input parameters and the return type:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust">fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
|
||||
if x.len() > y.len() {
|
||||
x
|
||||
@@ -305,7 +311,7 @@ satisfy this signature.</p>
|
||||
doing. If the function didn't actually return the longest string slice but
|
||||
instead always returned the first argument, we wouldn't need to specify a
|
||||
lifetime on <code>y</code>. This code compiles:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust">fn longest<'a>(x: &'a str, y: &str) -> &'a str {
|
||||
x
|
||||
}
|
||||
@@ -316,7 +322,7 @@ match one of the arguments' lifetime parameters. If the reference returned does
|
||||
refers to a value created within this function, and that would be a dangling
|
||||
reference since the value will go out of scope at the end of the function.
|
||||
Consider this attempted implementation of <code>longest</code>:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust,ignore">fn longest<'a>(x: &str, y: &str) -> &'a str {
|
||||
let result = String::from("really long string");
|
||||
result.as_str()
|
||||
@@ -352,7 +358,7 @@ would create dangling pointers or otherwise violate memory safety.</p>
|
||||
that use references as arguments or return values, then why did this function
|
||||
from the "String Slices" section of Chapter 4 compile? We haven't annotated any
|
||||
lifetimes here, yet Rust happily compiles this function:</p>
|
||||
<p>Filename: src/lib.rs</p>
|
||||
<p><span class="filename">Filename: src/lib.rs</span></p>
|
||||
<pre><code class="language-rust">fn first_word(s: &str) -> &str {
|
||||
let bytes = s.as_bytes();
|
||||
|
||||
@@ -417,7 +423,7 @@ holds a reference to another struct, <code>Config</code>, defined elsewhere. The
|
||||
<code>append_to_name</code> method does not need lifetime annotations even though the
|
||||
method has a reference as an argument and is returning a reference; the
|
||||
lifetime of the return value will be the lifetime of <code>self</code>:</p>
|
||||
<p>Filename: src/lib.rs</p>
|
||||
<p><span class="filename">Filename: src/lib.rs</span></p>
|
||||
<pre><code class="language-rust"># struct Config {}
|
||||
#
|
||||
struct App<'a> {
|
||||
|
||||
+1
-1
@@ -80,7 +80,7 @@ place where a pattern is used.</p>
|
||||
<p>We've seen statements like <code>let x = 5;</code> with a variable name in the <code>PATTERN</code>
|
||||
slot; a variable name is just a particularly humble form of pattern.</p>
|
||||
<p>Let’s try a more complex pattern. Change our example program to this:</p>
|
||||
<p>Filename: src/main.rs</p>
|
||||
<p><span class="filename">Filename: src/main.rs</span></p>
|
||||
<pre><code class="language-rust">fn main() {
|
||||
let (x, y) = (5, 6);
|
||||
|
||||
|
||||
+435
-328
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user