Next, make a new source file and call it main.rs. Rust files always end with
-the .rs extension. If you’re using more than one word in your filename, use
-an underscore to separate them. For example, you'd use hello_world.rs rather
-than helloworld.rs.
-
Now open the main.rs file you just created, and type the following code:
-
Filename: main.rs
+
Next, make a new source file and call it main.rs. Rust files always end with
+the .rs extension. If you’re using more than one word in your filename, use
+an underscore to separate them. For example, you'd use hello_world.rs rather
+than helloworld.rs.
+
Now open the main.rs file you just created, and type the following code:
This shows we have two files: the source code, with the .rs extension, and the
-executable (main.exe on Windows, main everywhere else). All that's left to
-do from here is run the main or main.exe file, like this:
+
This shows we have two files: the source code, with the .rs extension, and the
+executable (main.exe on Windows, main everywhere else). All that's left to
+do from here is run the main or main.exe file, like this:
$ ./main # or .\main.exe on Windows
-
If main.rs were your "Hello, world!" program, this would print Hello, world! to your terminal.
+
If main.rs were your "Hello, world!" program, this would print Hello, world! to your terminal.
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
ahead-of-time compiled 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 binaries. We've given hello_cargo
as the name for our project, and Cargo creates its files in a directory
of the same name that we can then go into.
-
If we list the files in the hello_cargo directory, we can see that Cargo has
-generated two files and one directory for us: a Cargo.toml and a src
-directory with a main.rs file inside. It has also initialized a new git
-repository in the hello_cargo directory for us, along with a .gitignore
+
If we list the files in the hello_cargo directory, we can see that Cargo has
+generated two files and one directory for us: a Cargo.toml and a src
+directory with a main.rs file inside. It has also initialized a new git
+repository in the hello_cargo directory for us, along with a .gitignore
file; you can change this to use a different version control system, or no
version control system, by using the --vcs flag.
-
Open up Cargo.toml in your text editor of choice. It should look something
+
Open up Cargo.toml in your text editor of choice. It should look something
like this:
-
Filename: Cargo.toml
+
Filename: Cargo.toml
[package]
name = "hello_cargo"
version = "0.1.0"
@@ -259,8 +259,8 @@ file.
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.
-
Now let's look at src/main.rs:
-
Filename: src/main.rs
+
Now let's look at src/main.rs:
+
Filename: src/main.rs
fn main() {
println!("Hello, world!");
}
@@ -269,41 +269,41 @@ the next chapter.
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:
-
Our code goes in the src directory
-
The top level contains a Cargo.toml configuration file
+
Our code goes in the src directory
+
The top level contains a Cargo.toml configuration file
-
Cargo expects your source files to live inside the src directory so that the
+
Cargo expects your source files to live inside the src 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.
If you started a project that doesn't use Cargo, as we did with our project in
-the hello_world directory, you can convert it to a project that does use
-Cargo by moving your code into the src directory and creating an appropriate
-Cargo.toml.
+the hello_world directory, you can convert it to a project that does use
+Cargo by moving your code into the src directory and creating an appropriate
+Cargo.toml.
Building and Running a Cargo Project
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:
This should have created an executable file in target/debug/hello_cargo (or
-target\debug\hello_cargo.exe on Windows), which you can run with this command:
+
This should have created an executable file in target/debug/hello_cargo (or
+target\debug\hello_cargo.exe on Windows), which you can run with this command:
$ ./target/debug/hello_cargo # or .\target\debug\hello_cargo.exe on Windows
Hello, world!
Bam! If all goes well, Hello, world! should print to the terminal once more.
Running cargo build for the first time also causes Cargo to create a new file
-at the top level called Cargo.lock, which looks like this:
-
Filename: Cargo.lock
+at the top level called Cargo.lock, which looks like this:
+
Filename: Cargo.lock
[root]
name = "hello_cargo"
version = "0.1.0"
-
Cargo uses the Cargo.lock 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.
+
Cargo uses the Cargo.lock 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.
We just built a project with cargo build and ran it with
./target/debug/hello_cargo, but we can also use cargo run to compile
and then run:
@@ -326,21 +326,21 @@ Hello, world!
Instead of using rustc, build a project using cargo build (or build and
run it in one step with cargo run)
Instead of the result of the build being put in the same directory as our
-code, Cargo will put it in the target/debug directory.
+code, Cargo will put it in the target/debug directory.
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.
Building for Release
When your project is finally ready for release, you can use cargo build --release to compile your project with optimizations. This will create an
-executable in target/release instead of target/debug. These optimizations
+executable in target/release instead of target/debug. 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 cargo build --release and benchmark with
-the executable in target/release.
+the executable in target/release.
Cargo as Convention
With simple projects, Cargo doesn't provide a whole lot of value over just
using rustc, but it will prove its worth as you continue. With complex
diff --git a/ch02-00-guessing-game-tutorial.html b/ch02-00-guessing-game-tutorial.html
index c8baae33b..b3727398a 100644
--- a/ch02-00-guessing-game-tutorial.html
+++ b/ch02-00-guessing-game-tutorial.html
@@ -89,7 +89,7 @@ as the first argument. The --bin flag tells Cargo to make a binary
similar to the one in Chapter 1. The second command changes to the new
project’s directory.
Look at the generated Cargo.toml file:
-
Filename: Cargo.toml
+
Filename: Cargo.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.
As you saw in Chapter 1, cargo new generates a “Hello, world!” program for
you. Check out the src/main.rs file:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
println!("Hello, world!");
}
@@ -121,7 +121,8 @@ before moving on to the next one.
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 src/main.rs.
-Listing 2-1: Code to get a guess from the user and print it out
-
+
+
Listing 2-1: Code to get a guess from the user and print it out
+
+
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
io (input/output) library from the standard library (which is known as std):
@@ -316,7 +318,7 @@ code that uses rand, we need to modify the Cargo.toml file
rand crate as a dependency. Open that file now and add the following line to
the bottom beneath the [dependencies] section header that Cargo created for
you:
-
Filename: Cargo.toml
+
Filename: Cargo.toml
[dependencies]
rand = "0.3.14"
@@ -332,6 +334,7 @@ for ^0.3.14, which means “any version that has a public API compa
version 0.3.14.”
Now, without changing any of the code, let’s build the project, as shown in
Listing 2-2:
-Listing 2-3: Code changes needed in order to generate a random number
-
+
+
Listing 2-3: Code changes needed in order to generate a random number
+
+
We’re adding a extern crate rand; line to the top that lets Rust know we’ll be
using that external dependency. This also does the equivalent of calling use rand, so now we can call anything in the rand crate by prefixing it with
rand::.
@@ -493,7 +499,8 @@ You guessed: 5
Comparing the Guess to the Secret Number
Now that we have user input and a random number, we can compare them. That
step is shown in Listing 2-4:
-Listing 2-4: Handling the possible return values of comparing two numbers
-
+
+
Listing 2-4: Handling the possible return values of comparing two numbers
+
+
The first new bit here is another use, bringing a type called
std::cmp::Ordering into scope from the standard library. Ordering is
another enum, like Result, but the variants for Ordering are Less,
@@ -591,7 +599,7 @@ not compare a string and a number type.
Ultimately, we want to convert the String 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 main function body:
-
Filename: src/main.rs
+
Filename: src/main.rs
extern crate rand;
use std::io;
@@ -684,7 +692,7 @@ Let’s change that by adding a loop!
Allowing Multiple Guesses with Looping
The loop keyword gives us an infinite loop. Add that now to give users more
chances at guessing the number:
-
Filename: src/main.rs
+
Filename: src/main.rs
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.
Quitting After a Correct Guess
Let’s program the game to quit when the user wins by adding a break:
-
Filename: src/main.rs
+
Filename: src/main.rs
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 println! that outputs the
secret number. Listing 2-5 shows the final code:
-
-Listing 2-5: Complete code of the guessing game
-
+
+
Listing 2-5: Complete code of the guessing game
+
+
Summary
At this point, you’ve successfully built the guessing game! Congratulations!
This project was a hands-on way to introduce you to many new Rust concepts:
diff --git a/ch03-00-common-programming-concepts.html b/ch03-00-common-programming-concepts.html
index fec72065e..dd9d63b09 100644
--- a/ch03-00-common-programming-concepts.html
+++ b/ch03-00-common-programming-concepts.html
@@ -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.
+
Keywords
The Rust language has a set of keywords 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.
+
diff --git a/ch03-01-variables-and-mutability.html b/ch03-01-variables-and-mutability.html
index b023d7287..897667039 100644
--- a/ch03-01-variables-and-mutability.html
+++ b/ch03-01-variables-and-mutability.html
@@ -78,7 +78,7 @@ you can’t change that value. To illustrate, let’s generate a new project cal
variables in your projects directory by using cargo new --bin variables.
Then, in your new variables directory, open src/main.rs and replace its
code with the following:
-
Filename: src/main.rs
+
Filename: src/main.rs
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.
For example, change src/main.rs to the following:
-
Filename: src/main.rs
+
Filename: src/main.rs
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
shadowed 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 let keyword as follows:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
let x = 5;
diff --git a/ch03-02-data-types.html b/ch03-02-data-types.html
index 4262dba25..9dcd05318 100644
--- a/ch03-02-data-types.html
+++ b/ch03-02-data-types.html
@@ -104,9 +104,10 @@ that the value it’s associated with should be a signed integer (hence the u 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, i32) can be used to declare the type of an integer value.
-
-Table 3-1: Integer Types in Rust
-
+
+
+
Table 3-1: Integer Types in Rust
+
Length
Signed
Unsigned
8-bit
i8
u8
16-bit
i16
u16
@@ -114,6 +115,7 @@ Table 3-1: Integer Types in Rust
64-bit
i64
u64
arch
isize
usize
+
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.
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
57u8, and _ as a visual separator, such as 1_000.
-
-Table 3-2: Integer Literals in Rust
-
+
+
+
Table 3-2: Integer Literals in Rust
+
Number literals
Example
Decimal
98_222
Hex
0xff
@@ -145,6 +148,7 @@ Table 3-2: Integer Literals in Rust
Binary
0b1111_0000
Byte (u8 only)
b'A'
+
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 i32: 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.
Here’s an example that shows floating-point numbers in action:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
let x = 2.0; // f64
@@ -173,7 +177,7 @@ your situation.
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 let statement:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
// addition
let sum = 5 + 10;
@@ -198,7 +202,7 @@ list of all operators that Rust provides.
As in most other programming languages, a boolean type in Rust has two possible
values: true and false. The boolean type in Rust is specified using bool.
For example:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
let t = true;
@@ -212,7 +216,7 @@ section.
So far we’ve only worked with numbers, but Rust supports letters too. Rust’s
char type is the language’s most primitive alphabetic type, and the following
code shows one way to use it:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
let c = 'z';
let z = 'ℤ';
@@ -237,7 +241,7 @@ a variety of types into one compound type.
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:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
let tup: (i32, f64, u8) = (500, 6.4, 1);
}
@@ -245,7 +249,7 @@ type annotations in this example:
The variable tup 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:
-
Filename: src/main.rs
+
Filename: src/main.rs
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
In addition to destructuring through pattern matching, we can also access a
tuple element directly by using a period (.) followed by the index of the
value we want to access. For example:
-
Filename: src/main.rs
+
Filename: src/main.rs
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.
In Rust, the values going into an array are written as a comma-separated list
inside square brackets:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
let a = [1, 2, 3, 4, 5];
}
@@ -305,7 +309,7 @@ an array because you know it will always contain 12 items:
Accessing Array Elements
An array is a single chunk of memory allocated on the stack. We can access
elements of an array using indexing, like this:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
let a = [1, 2, 3, 4, 5];
@@ -319,7 +323,7 @@ get the value 2 from index [1] in the array.
Invalid Array Element Access
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:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
let a = [1, 2, 3, 4, 5];
diff --git a/ch03-03-how-functions-work.html b/ch03-03-how-functions-work.html
index 23167b31b..b7c182019 100644
--- a/ch03-03-how-functions-work.html
+++ b/ch03-03-how-functions-work.html
@@ -75,7 +75,7 @@ declare new functions.
Rust code uses snake case 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:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
println!("Hello, world!");
@@ -110,7 +110,7 @@ called and its message is printed.
Function Arguments
Functions can also take arguments. The following rewritten version of
another_function shows what arguments look like in Rust:
-
Filename: src/main.rs
+
Filename: src/main.rs
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.
When you want a function to have multiple arguments, separate them inside the
function signature with commas, like this:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
another_function(5, 6);
}
@@ -174,19 +174,21 @@ instructions that perform some action and do not return a value. Expressions
evaluate to a resulting value. Let’s look at some examples.
Creating a variable and assigning a value to it with the let keyword is a
statement. In Listing 3-3, let y = 6; is a statement:
-
Filename: src/main.rs
+
+Filename: src/main.rs
fn main() {
let y = 6;
}
-
-Listing 3-3: A `main` function declaration containing one statement.
-
+
+
Listing 3-3: A main function declaration containing one statement.
+
+
Function definitions are also statements; the entire preceding example is a
statement in itself.
Statements do not return values. Therefore, you can’t assign a let statement
to another variable, as the following code tries to do:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
let x = (let y = 6);
}
@@ -214,7 +216,7 @@ statements: in Listing 3-3 that had the statement let y = 6;, 6. Calling a function is an
expression. Calling a macro is an expression. The block that we use to create
new scopes, {}, is an expression, for example:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
let x = 5;
@@ -244,7 +246,7 @@ values, but we do declare their type after an arrow (->). 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:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn five() -> i32 {
5
}
@@ -275,7 +277,7 @@ that line is the same as the following:
return value, but the body of the function is a lonely 5 with no semicolon
because it’s an expression whose value we want to return. Let’s look at another
example:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
let x = plus_one(5);
@@ -289,7 +291,7 @@ fn plus_one(x: i32) -> i32 {
Running this code will print The value of x is: 6. What happens if we place a
semicolon at the end of the line containing x + 1, changing it from an
expression to a statement?
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
let x = plus_one(5);
diff --git a/ch03-04-comments.html b/ch03-04-comments.html
index 2efacbaf1..b78d7f408 100644
--- a/ch03-04-comments.html
+++ b/ch03-04-comments.html
@@ -83,14 +83,14 @@ line. For comments that extend beyond a single line, you’ll need to include
// explain what’s going on.
Comments can also be placed at the end of lines containing code:
But you’ll more often see them used in this format, with the comment on a
separate line above the code it's annotating:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
// I’m feeling lucky today.
let lucky_number = 7;
diff --git a/ch03-05-control-flow.html b/ch03-05-control-flow.html
index abb875244..285f53472 100644
--- a/ch03-05-control-flow.html
+++ b/ch03-05-control-flow.html
@@ -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.”
Create a new project called branches in your projects directory to explore
the if expression. In the src/main.rs file, input the following:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
let number = 3;
@@ -123,7 +123,7 @@ condition was false
It’s also worth noting that the condition in this code must be a bool. To
see what happens if the condition isn’t a bool, try running the following
code:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
let number = 3;
@@ -153,7 +153,7 @@ languages such as Ruby and JavaScript. You must be explicit and always provide
if with a boolean as its condition. If we want the if code block to run
only when a number is not equal to 0, for example, we can change the if
expression to the following:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
let number = 3;
@@ -166,7 +166,7 @@ expression to the following:
Multiple Conditions with else if
We can have multiple conditions by combining if and else in an else if
expression. For example:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
let number = 6;
@@ -200,7 +200,8 @@ Rust branching construct called match for these cases.
Using if in a let statement
Because if is an expression, we can use it on the right side of a let
statement, for instance in Listing 3-4:
-
Filename: src/main.rs
+
+Filename: src/main.rs
fn main() {
let condition = true;
let number = if condition {
@@ -212,9 +213,10 @@ statement, for instance in Listing 3-4:
println!("The value of number is: {}", number);
}
-
-Listing 3-4: Assigning the result of an `if` expression to a variable
-
+
+
Listing 3-4: Assigning the result of an if expression to a variable
+
+
The number variable will be bound to a value based on the outcome of the if
expression. Run this code to see what happens:
$ cargo run
@@ -229,7 +231,7 @@ values that have the potential to be results from each arm of the ifif arm and the else
arm were i32 integers. But what happens if the types are mismatched, as in
the following example?
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
let condition = true;
@@ -274,7 +276,7 @@ experiment with loops, let’s make a new project called loops.
forever or until you explicitly tell it to stop.
As an example, change the src/main.rs file in your loops directory to look
like this:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
loop {
println!("again!");
@@ -311,7 +313,7 @@ program, if you’d like.
for it, and it’s called a while loop. The following example uses while: the
program loops three times, counting down each time. Then, after the loop, it
prints another message and exits:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
let mut number = 3;
@@ -330,7 +332,8 @@ true, the code runs; otherwise, it exits the loop.
Looping Through a Collection with for
You could use the while construct to loop over the elements of a collection,
such as an array. For example:
-
Filename: src/main.rs
+
+Filename: src/main.rs
fn main() {
let a = [10, 20, 30, 40, 50];
let mut index = 0;
@@ -342,9 +345,10 @@ such as an array. For example:
}
}
-
-Listing 3-5: Looping through each element of a collection using a `while` loop
-
+
+
Listing 3-5: Looping through each element of a collection using a while loop
+
+
Here, the code counts up through the elements in the array. It starts at index
0, and then loops until it reaches the final index in the array (that is,
when index < 5 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.
As a more efficient alternative, you can use a for loop and execute some code
for each item in a collection. A for loop looks like this:
-
Filename: src/main.rs
+
+Filename: src/main.rs
fn main() {
let a = [10, 20, 30, 40, 50];
@@ -376,9 +381,10 @@ for each item in a collection. A for loop looks like this:
}
}
-
-Listing 3-6: Looping through each element of a collection using a `for` loop
-
+
+
Listing 3-6: Looping through each element of a collection using a for loop
+
+
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.
Here’s what the countdown would look like using a for loop and another method
we’ve not yet talked about, rev, to reverse the range:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
for number in (1..4).rev() {
println!("{}!", number);
diff --git a/ch04-01-what-is-ownership.html b/ch04-01-what-is-ownership.html
index 39c94df49..e285157d5 100644
--- a/ch04-01-what-is-ownership.html
+++ b/ch04-01-what-is-ownership.html
@@ -284,11 +284,13 @@ under the covers in Figure 4-1. A String 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.
-
-
-Figure 4-1: Representation in memory of a `String` holding the value `"hello"`
-bound to `s1`
-
+
+
+
+
Figure 4-1: Representation in memory of a String holding the value "hello"
+bound to s1
+
+
The length is how much memory, in bytes, the contents of the String is
currently using. The capacity is the total amount of memory, in bytes, that the
String has gotten from the operating system. The difference between length
@@ -298,19 +300,23 @@ the capacity.
copy the pointer, the length, and the capacity that are on the stack. We do not
copy the data on the heap that the String’s pointer refers to. In other
words, it looks like figure 4-2.
-
-
-Figure 4-2: Representation in memory of the variable `s2` that has a copy of
-`s1`’s pointer, length and capacity
-
+
+
+
+
Figure 4-2: Representation in memory of the variable s2 that has a copy of
+s1’s pointer, length and capacity
+
+
And not 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 s2 = s1 could
potentially be very expensive if the data on the heap was large.
-
-
-Figure 4-3: Another possibility for what `s2 = s1` might do, if Rust chose to
-copy heap data as well.
-
+
+
+
+
Figure 4-3: Another possibility for what s2 = s1 might do, if Rust chose to
+copy heap data as well.
+
+
Earlier, we said that when a variable goes out of scope, Rust will
automatically call the drop 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 move. Here we would read this by saying that s1 was moved
into s2. So what actually happens looks like Figure 4-4.
-
-
-Figure 4-4: Representation in memory after `s1` has been invalidated
-
+
+
+
+
Figure 4-4: Representation in memory after s1 has been invalidated
+
+
That solves our problem! With only s2 valid, when it goes out of scope, it
alone will free the memory, and we’re done.
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 Copy:
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:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
let s = String::from("hello"); // s comes into scope.
@@ -439,7 +447,7 @@ the ownership rules prevent you from doing so.
Return Values and Scope
Returning values can also transfer ownership. Here’s an example with similar
annotations:
-
Filename: src/main.rs
+
Filename: src/main.rs
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.
It is possible to return multiple values using a tuple, like this:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
let s1 = String::from("hello");
diff --git a/ch04-02-references-and-borrowing.html b/ch04-02-references-and-borrowing.html
index ccf30e00e..a03bd8573 100644
--- a/ch04-02-references-and-borrowing.html
+++ b/ch04-02-references-and-borrowing.html
@@ -75,7 +75,7 @@ into calculate_length.
Here is how you would define and use a calculate_length function that takes a
reference to an object as an argument instead of taking ownership of the
argument:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
let s1 = String::from("hello");
@@ -94,10 +94,12 @@ function return value is gone. Next, note that we pass &s1 into
String.
These &s are references, and they allow you to refer to some value without
taking ownership of it. Figure 4-5 shows a diagram of this.
-
-
-Figure 4-5: `&String s` pointing at `String s1`
-
+
+
+
+
Figure 4-5: &String s pointing at String s1
+
+
Let’s take a closer look at the function call here:
# 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.
So what happens if we try to modify something we’re borrowing? Try this code
out. Spoiler alert: it doesn’t work!
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
let s = String::from("hello");
@@ -147,7 +149,7 @@ fn change(some_string: &String) {
to modify something we have a reference to.
Mutable References
We can fix this error with just a small tweak:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
let mut s = String::from("hello");
@@ -163,7 +165,7 @@ reference with &mut s and accept a mutable reference with 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:
-
Filename: src/main.rs
+
Filename: src/main.rs
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.
Let’s try to create a dangling reference:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
let reference_to_nothing = dangle();
}
diff --git a/ch04-03-slices.html b/ch04-03-slices.html
index fc6d7a25d..20a85ae61 100644
--- a/ch04-03-slices.html
+++ b/ch04-03-slices.html
@@ -82,7 +82,7 @@ returned.
ownership, so this is fine. But what should we return? We don’t really have a
way to talk about part of a string. We could return the index of the end of
the word, though. Let’s try that:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn first_word(s: &String) -> usize {
let bytes = s.as_bytes();
@@ -127,7 +127,7 @@ only a meaningful number in the context of the &String. In othe
because it’s a separate value from the String, there’s no guarantee that it
will still be valid in the future. Consider this program that uses this
first_word function:
-
Filename: src/main.rs
+
Filename: src/main.rs
# 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 let world = &s[6..11];, world would be a slice
that contains a pointer to the 6th byte of s and a length value of 5.
Figure 4-6 shows this in a diagram:
-
-
-Figure 4-6: String slice referring to part of a `String`
-
+
+
+
+
Figure 4-6: String slice referring to part of a String
+
+
With Rust’s .. range syntax, if you want to start at the first index (zero),
you can drop the value before the ... In other words, these are equal:
let s = String::from("hello");
@@ -212,7 +214,7 @@ let slice = &s[..];
With this in mind, let’s re-write first_word to return a slice. The type that
signifies “string slice” is written as &str:
-
Filename: src/main.rs
+
Filename: src/main.rs
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 first_word will throw a compile time error:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
let mut s = String::from("hello world");
@@ -292,7 +294,7 @@ to use the same function on both Strings and &strs
If we have a string slice, we can pass that as the argument directly. If we
have a String, we can pass a slice of the entire String. This makes our API
more general and useful without losing any functionality:
-
Filename: src/main.rs
+
Filename: src/main.rs
# fn first_word(s: &str) -> &str {
# let bytes = s.as_bytes();
#
diff --git a/ch05-00-structs.html b/ch05-00-structs.html
index d704ce88f..644c426d0 100644
--- a/ch05-00-structs.html
+++ b/ch05-00-structs.html
@@ -127,8 +127,8 @@ refactor our program until we're using structs instead.
Let’s make a new binary project with Cargo called rectangles 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 src/main.rs:
-
Filename: src/main.rs
+that to put into our project's src/main.rs:
+
Filename: src/main.rs
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.
We’ve already discussed one way we might do that in Chapter 3: tuples. Here’s a
version of our program which uses tuples:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
let rect1 = (50, 30);
@@ -193,7 +193,7 @@ in our code.
Refactoring with Structs: Adding More Meaning
Here is where we bring in structs. We can transform our tuple into a data
type with a name for the whole as well as names for the parts:
-
Filename: src/main.rs
+
Filename: src/main.rs
struct Rectangle {
length: u32,
width: u32,
@@ -232,7 +232,7 @@ index values of 0 and 1. This is a win for clarity.It'd be nice to be able to print out an instance of our Rectangle while we're
debugging our program and see the values for all its fields. Let's try using
the println! macro as we have been and see what happens:
-
Filename: src/main.rs
+
Filename: src/main.rs
struct Rectangle {
length: u32,
width: u32,
diff --git a/ch06-00-enums.html b/ch06-00-enums.html
index ee4a45999..e94b0adbe 100644
--- a/ch06-00-enums.html
+++ b/ch06-00-enums.html
@@ -180,6 +180,7 @@ route(IpAddrKind::V6);
address type, at the moment we don’t have a way to store the actual data of
the IP address; we only know what kind it is. Given that you just learned
about structs, you might tackle this problem as in Listing 6-1:
+
-Listing 6-1: Storing the data and type of an IP address using a `struct`
-
+
+
Listing 6-1: Storing the data and type of an IP address using a struct
+
+
Here, we've defined a struct IpAddr that has two fields: a kind field that
is of type IpAddrKind (the enum we defined previously), and an address
diff --git a/ch06-02-match.html b/ch06-02-match.html
index f60c633a6..6e500c405 100644
--- a/ch06-02-match.html
+++ b/ch06-02-match.html
@@ -82,6 +82,7 @@ execution.
match! 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:
+
-Listing 6-2: An enum and a `match` expression that has the variants of the enum
-as its patterns.
-
+
+
Listing 6-2: An enum and a match expression that has the variants of the enum
+as its patterns.
+
+
@@ -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 enum
by changing the Quarter variant to include a State value stored inside it
as we've done here in Listing 6-3:
+
#[derive(Debug)] // So we can inspect the state in a minute
enum UsState {
Alabama,
@@ -174,10 +177,11 @@ enum Coin {
Quarter(UsState),
}
-
-Listing 6-3: A `Coin` enum where the `Quarter` variant also holds a `UsState`
-value
-
+
+
Listing 6-3: A Coin enum where the Quarter variant also holds a UsState
+value
+
+
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 None value and not attempt to perfor
operations.
This function is very easy to write, thanks to match, and will look like
Listing 6-4:
+
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);
-
-Listing 6-4: A function that uses a `match` expression on an `Option`
-
+
+
Listing 6-4: A function that uses a match expression on an Option<i32>
+
+
Matching Some(T)
Let's examine the first execution of plus_one in more detail. In the above
diff --git a/ch07-01-mod-and-the-filesystem.html b/ch07-01-mod-and-the-filesystem.html
index 05e19bbbf..f669f5ce9 100644
--- a/ch07-01-mod-and-the-filesystem.html
+++ b/ch07-01-mod-and-the-filesystem.html
@@ -83,7 +83,7 @@ $ cd communicator
Notice that Cargo generated src/lib.rs instead of src/main.rs. Inside
src/lib.rs we’ll find this:
-
Filename: src/lib.rs
+
Filename: src/lib.rs
#[cfg(test)]
mod tests {
#[test]
@@ -106,7 +106,7 @@ you have for your code.
named network that contains the definition of a function called connect.
Every module definition in Rust starts with the mod keyword. Add this code to
the beginning of the lib.rs file, above the test code:
-
Filename: src/lib.rs
+
Filename: src/lib.rs
mod network {
fn connect() {
}
@@ -121,7 +121,8 @@ specify the module and use the namespace syntax ::, like so:
We can also have multiple modules, side-by-side, in the same src/lib.rs file.
For example, to have a client module too, that also has a function named
connect, we can add:
-
Filename: src/lib.rs
+
+Filename: src/lib.rs
mod network {
fn connect() {
}
@@ -132,22 +133,24 @@ mod client {
}
}
-
-Listing 7-1: The `network` module and the `client` module defined side-by-side
-in *src/lib.rs*
-
+
+
Listing 7-1: The network module and the client module defined side-by-side
+in src/lib.rs
+
+
Now we have a network::connect function and a client::connect function.
These can have completely different functionality, and the function names do
not conflict with each other since they’re in different modules.
While in this case, we’re building a library, there's nothing special about
-lib.rs. We could also make use of submodules in a main.rs as well. In fact,
+lib.rs. We could also make use of submodules in a main.rs 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 client code and its connect function might make more sense to users of
our library if it was inside the network namespace instead, like so:
-
Filename: src/lib.rs
+
+Filename: src/lib.rs
mod network {
fn connect() {
}
@@ -158,15 +161,16 @@ our library if it was inside the network namespace instead, like so
}
}
-
-Listing 7-2: Moving the `client` module inside of the `network` module
-
+
+
Listing 7-2: Moving the client module inside of the network module
+
+
In your src/lib.rs file, replace the existing mod network and mod client
definitions with this one that has the client module as an inner module of
network. Now we have the functions network::connect and
network::client::connect: again, the two functions named connect don’t
conflict with each other since they’re in different namespaces.
-
In this way, modules form a hierarchy. The contents of src/lib.rs are at the
+
In this way, modules form a hierarchy. The contents of src/lib.rs 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:
@@ -191,7 +195,8 @@ structure you would like.
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
src/lib.rs. For this example, we will start with this code in src/lib.rs:
-
File: src/lib.rs
+
+File: src/lib.rs
mod client {
fn connect() {
}
@@ -207,10 +212,11 @@ mod network {
}
}
-
-Listing 7-3: Three modules, `client`, `network`, and `network::server` all
-defined in *src/lib.rs*
-
+
+
Listing 7-3: Three modules, client, network, and network::server all
+defined in src/lib.rs
+
+
which has this module hierarchy:
communicator
├── client
@@ -223,7 +229,7 @@ This would be a good reason to pull each of the client, netwo
server modules out of src/lib.rs and into their own files. Let’s start by
extracting the client module into another file. First, replace the client
module code in src/lib.rs with the following:
-
File: src/lib.rs
+
File: src/lib.rs
mod client;
mod network {
@@ -242,15 +248,15 @@ braces and definitions inside the client module and replacing them
semicolon, we’re letting Rust know to look in another location for the code
defined inside that module.
So now we need to create the external file with that module name. Create a
-client.rs file in your src/ directory, then open it up and enter the
+client.rs file in your src/ directory, then open it up and enter the
following, which is the connect function in the client module that we
removed in the previous step:
-
File: src/client.rs
+
File: src/client.rs
fn connect() {
}
Note that we don’t need a mod declaration in this file; that’s because we
-already declared the client module with mod in src/lib.rs. This file just
+already declared the client module with mod in src/lib.rs. This file just
provides the contents of the client module. If we put a mod client here,
we’d be giving the client module its own submodule named client!
Rust only knows to look in src/lib.rs 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!
Let’s extract the network module into its own file next, using the same
-pattern. In src/lib.rs, delete the body of the network module and add a
+pattern. In src/lib.rs, delete the body of the network module and add a
semicolon to the declaration, like so:
-
Filename: src/lib.rs
+
Filename: src/lib.rs
mod client;
mod network;
-
Then create a new src/network.rs file and enter the following:
-
Filename: src/network.rs
+
Then create a new src/network.rs file and enter the following:
+
Filename: src/network.rs
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
src/network.rs to have mod server; instead of the server module’s
contents:
-
Filename: src/network.rs
+
Filename: src/network.rs
fn connect() {
}
mod server;
-
Then create a src/server.rs file and enter the contents of the server
+
Then create a src/server.rs file and enter the contents of the server
module that we extracted:
-
Filename: src/server.rs
+
Filename: src/server.rs
fn connect() {
}
When we try to cargo build, we’ll get this error:
+
$ 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;
| ^^^^^^
-
-Listing 7-4: Error when trying to extract the `server` submodule into
-*src/server.rs*
-
+
+
Listing 7-4: Error when trying to extract the server submodule into
+src/server.rs
+
+
The error says we cannot declare a new module at this location and is
-pointing to the mod server; line in src/network.rs. So src/network.rs is
-different than src/lib.rs somehow; let’s keep reading to understand why.
+pointing to the mod server; line in src/network.rs. So src/network.rs is
+different than src/lib.rs somehow; let’s keep reading to understand why.
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:
@@ -388,7 +396,7 @@ same as it did when we had all the code in src/lib.rs in Listing 7-3:
also change the src/network.rs file into the src/network/mod.rs file, and
also put the code for network::server in the network directory in
src/network/server.rs, instead of just being able to extract the
-network::server into src/server.rs? The reason is that Rust wouldn’t be
+network::server into src/server.rs? The reason is that Rust wouldn’t be
able to tell that server was supposed to be a submodule of network if the
server.rs file was in the src 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 src/client.rs is unambiguously the code that belongs to the
If a module named foo has no submodules, you should put the declarations
-for foo in a file named foo.rs.
+for foo in a file named foo.rs.
If a module named foo does have submodules, you should put the declarations
-for foo in a file named foo/mod.rs.
+for foo in a file named foo/mod.rs.
The first two rules apply recursively, so that if a module named foo has a
submodule named bar and bar does not have submodules, you should have the
-following files in your src directory:
+following files in your src directory:
├── foo
│ ├── bar.rs (contains the declarations in `foo::bar`)
│ └── mod.rs (contains the declarations in `foo`, including `mod bar`)
diff --git a/ch07-02-controlling-visibility-with-pub.html b/ch07-02-controlling-visibility-with-pub.html
index 0281e509b..fef01d9b6 100644
--- a/ch07-02-controlling-visibility-with-pub.html
+++ b/ch07-02-controlling-visibility-with-pub.html
@@ -100,8 +100,8 @@ another project and not our own.
To understand why this program invokes these warnings, let’s try using the
connect 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 src/main.rs file containing this code:
-
Filename: src/main.rs
+by making a src/main.rs file containing this code:
+
Filename: src/main.rs
extern crate communicator;
fn main() {
@@ -144,8 +144,8 @@ unused.
the declaration of the item we want to make public. We’ll focus on fixing the
warning that tells us that client::connect has gone unused for now, as well
as the “module client is private” error from our binary crate. Modify
-src/lib.rs to make the client module public, like so:
-
Filename: src/lib.rs
+src/lib.rs to make the client module public, like so:
+
Filename: src/lib.rs
pub mod client;
mod network;
@@ -161,7 +161,7 @@ error: function `connect` is private
Hooray! We have a different error! Yes, different error messages are a cause
for celebration. The new error says “function connect is private”, so let’s
edit src/client.rs to make client::connect public too:
-
Filename: src/client.rs
+
Filename: src/client.rs
pub fn connect() {
}
@@ -187,8 +187,8 @@ accidentally removed all places within your library where this function is
called.
In our case though, we do want the other two functions to be part of our
crate’s public API, so let’s mark them as pub as well to try to get rid of
-the remaining warnings. Modify src/network/mod.rs to be:
-
Filename: src/network/mod.rs
+the remaining warnings. Modify src/network/mod.rs to be:
+
Filename: src/network/mod.rs
pub fn connect() {
}
@@ -213,7 +213,7 @@ within the module, but the network module that the function resides
public. We’re working from the interior of the library out this time, where
with client::connect we worked from the outside in. We need to change
src/lib.rs to make network public too:
-
Filename: src/lib.rs
+
Filename: src/lib.rs
pub mod client;
pub mod network;
@@ -236,8 +236,9 @@ child modules.
Privacy Examples
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 src/lib.rs:
-
Filename: src/lib.rs
+project and enter the code in Listing 7-5 into your new project’s src/lib.rs:
+
+Filename: src/lib.rs
Listing 7-5: Examples of private and public functions, some of which are
+incorrect
+
+
Before you try to compile this code, make a guess about which lines in try_me
function will have errors. Then try compiling to see if you were right, and read
on for discussion of the errors!
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 namespaces function shown
here in Listing 7-6.
-
Filename: src/main.rs
+
+Filename: src/main.rs
pub mod a {
pub mod series {
pub mod of {
@@ -84,17 +85,18 @@ fn main() {
a::series::of::namespaces();
}
-
-Listing 7-6: Calling a function by fully specifying its enclosing module’s
-namespaces
-
+
+
Listing 7-6: Calling a function by fully specifying its enclosing module’s
+namespaces
+
+
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.
Concise Imports with use
Rust’s use 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 a::series::of namespace into a binary crate’s root scope:
-
Filename: src/main.rs
+
Filename: src/main.rs
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.
Using super to Access a Parent Module
As you now know, when you create a library crate, Cargo makes a tests module
for you. Let’s go into more detail about that now. In your communicator
-project, open src/lib.rs.
-
Filename: src/lib.rs
+project, open src/lib.rs.
+
Filename: src/lib.rs
pub mod client;
pub mod network;
@@ -201,7 +203,7 @@ looks like this:
Tests are for exercising the code within our library, so let’s try to call
our client::connect function from this it_works function, even though
we’re not going to be checking any functionality right now:
-
Filename: src/lib.rs
+
Filename: src/lib.rs
#[cfg(test)]
mod tests {
#[test]
@@ -254,7 +256,7 @@ functionality changes the path you give to use so that it is relati
parent module instead of to the root module.
For these reasons, in the tests module especially, use super::something is
usually the way to go. So now our test looks like this:
-
Filename: src/lib.rs
+
Filename: src/lib.rs
#[cfg(test)]
mod tests {
use super::client;
diff --git a/ch09-01-unrecoverable-errors-with-panic.html b/ch09-01-unrecoverable-errors-with-panic.html
index 994881f44..4c7aebf28 100644
--- a/ch09-01-unrecoverable-errors-with-panic.html
+++ b/ch09-01-unrecoverable-errors-with-panic.html
@@ -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 panic = 'abort' to the appropriate
-[profile] sections in your Cargo.toml.
+[profile] sections in your Cargo.toml.
Let's try out calling panic!() with a simple program:
+
Filename: src/main.rs
fn main() {
panic!("crash and burn");
}
@@ -103,10 +104,11 @@ error: Process didn't exit successfully: `target/debug/panic` (exit code: 101)
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:
-src/main.rs, line two.
+src/main.rs, line two.
But that only shows us the exact line that called panic!. That's not always
useful. Let's look at another example to see what it's like when a panic!
call comes from code we call instead of from our code directly:
+
Filename: src/main.rs
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)
-
This points at a file we didn't write, ../src/libcollections/vec.rs. That's
+
This points at a file we didn't write, ../src/libcollections/vec.rs. That's
the implementation of Vec<T> 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.
That's what the next line, the note is about. If we set the RUST_BACKTRACE
environment variable, we'll get a backtrace of exactly how the error happend.
Let's try that. Listing 9-1 shows the output:
-Listing 9-1: The backtrace generated by a call to `panic!` displayed when
-the environment variable `RUST_BACKTRACE` is set
-
+
+
Listing 9-1: The backtrace generated by a call to panic! displayed when
+the environment variable RUST_BACKTRACE is set
+
+
That's a lot of output! Line 11 of the backtrace points to the line in our
-project causing the problem: src/main.rs line four. The key to reading the
+project causing the problem: src/main.rs 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
diff --git a/ch09-02-recoverable-errors-with-result.html b/ch09-02-recoverable-errors-with-result.html
index 9192cdc1b..55df7ea8c 100644
--- a/ch09-02-recoverable-errors-with-result.html
+++ b/ch09-02-recoverable-errors-with-result.html
@@ -89,21 +89,26 @@ in more detail in Chapter 10. What you need to know for right now is that the
T that is what we want to return in the success case, and any type E that
is what we want to return in the error case.
Listing 9-2 shows an example of something that might fail: opening a file.
+
+Filename: src/main.rs
use std::fs::File;
fn main() {
let f = File::open("hello.txt");
}
-
-Listing 9-2: Opening a file
-
+
+
Listing 9-2: Opening a file
+
+
The type of f in this example is a Result, because there are many ways in
which opening a file can fail. For example, unless we created hello.txt, this
file does not yet exist. Before we can do anything with our File, we need to
extract it out of the result. Listing 9-3 shows one way to handle the Result
with a basic tool: the match expression that we learned about in Chapter 6.
-Listing 9-3: Using a `match` expression to handle the `Result` variants we might have
-
+
+
Listing 9-3: Using a match expression to handle the Result variants we
+might have
+
+
If we see an Ok, we can return the inner file out of the Ok variant. If
we see Err, we have to decide what to do with it. The simplest thing is to
turn our error into a panic! 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
kind that we can call to get an io::ErrorKind
value that we can use to handle different causes of an Err returned from
File::open differently as in Listing 9-4:
+
+Filename: src/main.rs
use std::fs::File;
use std::io::ErrorKind;
@@ -157,9 +166,10 @@ error),
};
}
-
-Listing 9-4: Handling different kinds of errors in different ways
-
+
+
Listing 9-4: Handling different kinds of errors in different ways
+
+
This example uses a match guard with the second arm's pattern to add a
condition that further refines the pattern. The ref in the pattern is needed
@@ -174,6 +184,7 @@ communicate intent well. The Result<T, E> 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 unwrap():
+
Filename: src/main.rs
use std::fs::File;
fn main() {
@@ -187,6 +198,7 @@ the error message: expect(). Using expect() instead of
providing good error messages can convey your intent and make tracking down the
source of a panic easier. expect() looks like this:
+
Filename: src/main.rs
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:
+
# use std::fs::File;
# use std::io;
# use std::io::Read;
@@ -247,9 +260,10 @@ fn read_username_from_file() -> Result<String, io::Error> {
}
}
-
-Listing 9-5: A function that returns errors to the calling code using `match`
-
+
+
Listing 9-5: A function that returns errors to the calling code using match
+
+
Since the Result type has two type parameters, we need to include them both
in our function signature. In this case, File::open and read_to_string
return std::io::Error as the value inside the Err variant, so we will also
@@ -265,6 +279,7 @@ as in Listing 9-6, and it would have the same functionality as the match
expressions:
+
# 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)
}
-
-Listing 9-6: A function that returns errors to the calling code using `try!`
-
+
+
Listing 9-6: A function that returns errors to the calling code using try!
+
+
Or as in Listing 9-7, which uses the question mark operator:
-Listing 9-7: A function that returns errors to the calling code using `?`
-
+
+
Listing 9-7: A function that returns errors to the calling code using ?
+
+
The ? operator at the end of the open call does the same thing as the
example that uses match and the example that uses the try! macro: It will
return the value inside an Ok to the binding f, but will return early out
@@ -324,6 +342,7 @@ used in functions that return a Result, since they expand to the sa
expression we saw above that had a potential early return of an Err value.
Let's look at what happens if we try to use try! in the main function,
which you'll recall has a return type of ():
+
Filename: src/main.rs
# use std::fs::File;
fn main() {
let f = try!(File::open("hello.txt"));
diff --git a/ch09-03-to-panic-or-not-to-panic.html b/ch09-03-to-panic-or-not-to-panic.html
index d9edb7f31..7b725028b 100644
--- a/ch09-03-to-panic-or-not-to-panic.html
+++ b/ch09-03-to-panic-or-not-to-panic.html
@@ -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 Guess type that will only create an instance of Guess
if the new function gets a value between 1 and 100:
+
-Listing 9-8: A `Guess` type that will only hold values between 1 and 100
-
+
+
Listing 9-8: A Guess type that will only hold values between 1 and 100
+
+
If code calling Guess::new passed in a value that was not between 1 and 100,
that would be a violation of the contract that Guess::new is relying on. This
function needs to signal to the calling code that it has a bug somewhere
diff --git a/ch10-00-generics.html b/ch10-00-generics.html
index e1231a48a..c1ccdb863 100644
--- a/ch10-00-generics.html
+++ b/ch10-00-generics.html
@@ -84,7 +84,8 @@ in this chapter.
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:
-
Filename: src/main.rs
+
+Filename: src/main.rs
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:
println!("The largest number is {}", largest);
}
-
-Listing 10-1: Code to find the largest number in a list of numbers
-
+
+
Listing 10-1: Code to find the largest number in a list of numbers
+
+
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:
-
Filename: src/main.rs
+
Filename: src/main.rs
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
largest. 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:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn largest(numbers: Vec<i32>) {
let mut largest = numbers[0];
diff --git a/ch10-01-syntax.html b/ch10-01-syntax.html
index 068a78f5c..fc97a3857 100644
--- a/ch10-01-syntax.html
+++ b/ch10-01-syntax.html
@@ -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 Option enum with a Some variant that can
only hold an i32. We'll call this enum OptionalNumber:
-
Filename: src/main.rs
+
Filename: src/main.rs
enum OptionalNumber {
Some(i32),
None,
@@ -106,7 +106,7 @@ fn main() {
would have to duplicate code to define a separate Option enum type for each
type we wanted to be able to hold in the Some variants. For example, here is
how we could define and use OptionalFloatingPointNumber:
-
Filename: src/main.rs
+
Filename: src/main.rs
enum OptionalFloatingPointNumber {
Some(f64),
None,
@@ -197,7 +197,7 @@ is the compiler will see that we've used two kinds of Option<T>Option<T> into Option_i32 and Option_f64, 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:
-
Filename: src/main.rs
+
Filename: src/main.rs
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 Point
struct that could hold x and y coordinate values that are any type:
-
-Listing 10-2: A `Point` struct that holds `x` and `y` values of type `T`
-
+
+
Listing 10-2: A Point struct that holds x and y values of type T
+
+
The syntax is the same with structs: add a <T> after the name of the struct,
then use T in the definition where you want to use that generic type instead
of a specific type.
@@ -261,7 +263,8 @@ type of x:
declare multiple type parameters within the angle brackets, separated by a
comma. Listing 10-3 shows how to define a Point that can have different types
for x and y:
-
Filename: src/main.rs
+
+Filename: src/main.rs
struct Point<X, Y> {
x: X,
y: Y,
@@ -273,10 +276,11 @@ fn main() {
let p = Point { x: 5, y: 20.0 };
}
-
-Listing 10-2: A `Point` struct that holds an `x` value of type `X` and a `y`
-value of type `Y`
-
+
+
Listing 10-3: A Point struct that holds an x value of type X and a y
+value of type Y
+
+
Now x will have the type of X, and y will have the type of Y, and we
can instantiate a Point with an i32 for x and an f64 for y.
We can make enums with multiple type parameters as well. Recall the enum
@@ -322,17 +326,19 @@ one:
There's one problem though. We've got some function definitions that work,
but if we try to use value 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
value in its body:
-
Filename: src/lib.rs
+
+Filename: src/lib.rs
fn show_anything<T>(value: T) {
println!("I have something to show you!");
println!("It's: {}", value);
}
-
-Listing 10-3: A `show_anything` function definition that does not yet compile
-
+
+
Listing 10-4: A show_anything function definition that does not yet compile
+
+
Compiling this definition results in an error:
error[E0277]: the trait bound `T: std::fmt::Display` is not satisfied
--> <anon>:3:37
diff --git a/ch10-02-traits.html b/ch10-02-traits.html
index 703dd6467..cb54e3358 100644
--- a/ch10-02-traits.html
+++ b/ch10-02-traits.html
@@ -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.
-
Here's an example definition of a trait named Printable that has a method
-named print:
-
Filename: src/lib.rs
+
Listing 10-5 has an example definition of a trait named Printable with a
+method named print:
+
+Filename: src/lib.rs
trait Printable {
fn print(&self);
}
-
-Listing 10-4: A `Printable` trait definition with one method, `print`
-
+
+
Listing 10-5: A Printable trait definition with one method, print
+
+
We declare a trait with the trait 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
Implementing a trait for a particular type looks similar to implementing
methods on a type since it's also done with the impl keyword, but we specify
the trait name as well. Inside the impl 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 Printable 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 Printable trait from Listing 10-5 (that only has
the print method) for a Temperature enum:
-
Filename: src/lib.rs
+
+Filename: src/lib.rs
# trait Printable {
# fn print(&self);
# }
@@ -119,13 +122,14 @@ impl Printable for Temperature {
}
}
-
-Listing 10-5: Implementing the `Printable` trait on a `Temperature` enum
-
+
+
Listing 10-6: Implementing the Printable trait on a Temperature enum
+
+
In the same way impl 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:
-
Filename: src/main.rs
+
Filename: src/main.rs
# trait Printable {
# fn print(&self);
# }
@@ -162,14 +166,15 @@ brought the trait we wanted into our current scope with use.
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 print_anything function
-definition. This is similar to the show_anything function from Listing 10-3,
+a trait. To illustrate this, Listing 10-7 has a print_anything function
+definition. This is similar to the show_anything function from Listing 10-4,
but this function has a trait bound on the generic type T and uses the
print 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 print in the
function body:
-
-Listing 10-6: A `print_anything` function that uses the trait bound `Printable`
-on type `T`
-
+
+
Listing 10-7: A print_anything function that uses the trait bound Printable
+on type T
+
+
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 (:) and then specify the name of the trait. This function now specifies
@@ -190,10 +196,10 @@ that it takes a value parameter that can be of any type, as long as
implements the trait Printable. We need to specify the Printable trait in
the type name declarations because we want to be able to call the print
method that is part of the Printable trait.
-
Now we are able to call the print_anything function from Listing 10-6 and
+
Now we are able to call the print_anything function from Listing 10-7 and
pass it a Temperature instance as the value parameter, since we implemented
-the trait Printable on Temperature in Listing 10-5:
-
Filename: src/main.rs
+the trait Printable on Temperature in Listing 10-6:
+
Filename: src/main.rs
# trait Printable {
# fn print(&self);
# }
@@ -241,10 +247,11 @@ standard library, and they're used for many, many different things. For
example, our Printable trait is similar to one of those traits, Display.
And in fact, that's how println! decides how to format things with {}. The
Display trait has a fmt method that determines how to format something.
-
Listing 10-7 shows our original example from Listing 10-3, but this time using
+
Listing 10-8 shows our original example from Listing 10-3, but this time using
the standard library's Display trait in the trait bound on the generic type
in the show_anything function:
-Listing 10-7: The `show_anything` function with trait bounds
-
+
+
Listing 10-8: The show_anything function with trait bounds
+
+
Now that this function specifies that T can be any type as long as that type
implements the Display trait, this code will compile.
Multiple Trait Bounds and where Syntax
@@ -276,8 +284,8 @@ Listing 10-3 referred to it:
The where syntax moves the trait bounds after the function arguments list.
This definition of show_anything means the exact same thing as the definition
-in Listing 10-7, just said a different way:
-
Filename: src/lib.rs
+in Listing 10-8, just said a different way:
+
Filename: src/lib.rs
use std::fmt::Display;
fn show_anything<T>(value: T) where T: Display {
diff --git a/ch10-03-lifetime-syntax.html b/ch10-03-lifetime-syntax.html
index ed143609b..514d648f3 100644
--- a/ch10-03-lifetime-syntax.html
+++ b/ch10-03-lifetime-syntax.html
@@ -110,6 +110,8 @@ scope. The outer scope declares a variable named r with no initial
the inner scope declares a variable named x with the initial value of 5.
Inside the inner scope, we attempt to set the value of r to a reference to
x. Then the inner scope ends and we attempt to print out the value in r:
+
+Filename: src/lib.rs
{
let r;
@@ -121,9 +123,10 @@ Inside the inner scope, we attempt to set the value of r to a refer
println!("r: {}", r);
}
-
-Listing 10-8: An attempt to use a reference whose value has gone out of scope
-
+
+
Listing 10-8: An attempt to use a reference whose value has gone out of scope
+
+
If we compile this code, we get an error:
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 The longest string is abcd once
we've implemented the longest function:
-
-Listing 10-9: A `main` function that demonstrates how we'd like to use the
-`longest` function
-
+
+
Listing 10-9: A main function that demonstrates how we'd like to use the
+longest function
+
+
Note that we want the function to take string slices because we don't want the
longest function to take ownership of its arguments, and we want the function
to be able to accept slices of a String (like a) is as well as string
@@ -257,6 +262,7 @@ literals (b). Refer back to the "String Slices as Arguments&qu
Chapter 4 for more discussion about why these are the arguments we want.
Here's the start of an implementation of the longest function that won't
compile yet:
+
Filename: src/main.rs
fn longest(x: &str, y: &str) -> &str {
if x.len() > y.len() {
x
@@ -280,7 +286,7 @@ know either, since in the if block in the body of this function ret
reference to x and the else block returns a reference to y! 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:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() {
x
@@ -305,7 +311,7 @@ satisfy this signature.
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 y. This code compiles:
-
Filename: src/main.rs
+
Filename: src/main.rs
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 longest:
-
Filename: src/main.rs
+
Filename: src/main.rs
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.
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:
-
Filename: src/lib.rs
+
Filename: src/lib.rs
fn first_word(s: &str) -> &str {
let bytes = s.as_bytes();
@@ -417,7 +423,7 @@ holds a reference to another struct, Config, defined elsewhere. The
append_to_name 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 self:
-
Filename: src/lib.rs
+
Filename: src/lib.rs
# struct Config {}
#
struct App<'a> {
diff --git a/chXX-patterns.html b/chXX-patterns.html
index a10db6108..129938277 100644
--- a/chXX-patterns.html
+++ b/chXX-patterns.html
@@ -80,7 +80,7 @@ place where a pattern is used.
We've seen statements like let x = 5; with a variable name in the PATTERN
slot; a variable name is just a particularly humble form of pattern.
Let’s try a more complex pattern. Change our example program to this:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
let (x, y) = (5, 6);
diff --git a/print.html b/print.html
index 87ad482ad..e2a76a344 100644
--- a/print.html
+++ b/print.html
@@ -179,12 +179,12 @@ $ cd hello_world
> cd hello_world
Writing and Running a Rust Program
-
Next, make a new source file and call it main.rs. Rust files always end with
-the .rs extension. If you’re using more than one word in your filename, use
-an underscore to separate them. For example, you'd use hello_world.rs rather
-than helloworld.rs.
-
Now open the main.rs file you just created, and type the following code:
-
Filename: main.rs
+
Next, make a new source file and call it main.rs. Rust files always end with
+the .rs extension. If you’re using more than one word in your filename, use
+an underscore to separate them. For example, you'd use hello_world.rs rather
+than helloworld.rs.
+
Now open the main.rs file you just created, and type the following code:
This shows we have two files: the source code, with the .rs extension, and the
-executable (main.exe on Windows, main everywhere else). All that's left to
-do from here is run the main or main.exe file, like this:
+
This shows we have two files: the source code, with the .rs extension, and the
+executable (main.exe on Windows, main everywhere else). All that's left to
+do from here is run the main or main.exe file, like this:
$ ./main # or .\main.exe on Windows
-
If main.rs were your "Hello, world!" program, this would print Hello, world! to your terminal.
+
If main.rs were your "Hello, world!" program, this would print Hello, world! to your terminal.
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
ahead-of-time compiled language, which means that you can compile a program,
@@ -310,15 +310,15 @@ executable application, as opposed to a library. Executables are binary
executable files often called just binaries. We've given hello_cargo
as the name for our project, and Cargo creates its files in a directory
of the same name that we can then go into.
-
If we list the files in the hello_cargo directory, we can see that Cargo has
-generated two files and one directory for us: a Cargo.toml and a src
-directory with a main.rs file inside. It has also initialized a new git
-repository in the hello_cargo directory for us, along with a .gitignore
+
If we list the files in the hello_cargo directory, we can see that Cargo has
+generated two files and one directory for us: a Cargo.toml and a src
+directory with a main.rs file inside. It has also initialized a new git
+repository in the hello_cargo directory for us, along with a .gitignore
file; you can change this to use a different version control system, or no
version control system, by using the --vcs flag.
-
Open up Cargo.toml in your text editor of choice. It should look something
+
Open up Cargo.toml in your text editor of choice. It should look something
like this:
-
Filename: Cargo.toml
+
Filename: Cargo.toml
[package]
name = "hello_cargo"
version = "0.1.0"
@@ -342,8 +342,8 @@ file.
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.
-
Now let's look at src/main.rs:
-
Filename: src/main.rs
+
Now let's look at src/main.rs:
+
Filename: src/main.rs
fn main() {
println!("Hello, world!");
}
@@ -352,41 +352,41 @@ the next chapter.
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:
-
Our code goes in the src directory
-
The top level contains a Cargo.toml configuration file
+
Our code goes in the src directory
+
The top level contains a Cargo.toml configuration file
-
Cargo expects your source files to live inside the src directory so that the
+
Cargo expects your source files to live inside the src 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.
If you started a project that doesn't use Cargo, as we did with our project in
-the hello_world directory, you can convert it to a project that does use
-Cargo by moving your code into the src directory and creating an appropriate
-Cargo.toml.
+the hello_world directory, you can convert it to a project that does use
+Cargo by moving your code into the src directory and creating an appropriate
+Cargo.toml.
Building and Running a Cargo Project
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:
This should have created an executable file in target/debug/hello_cargo (or
-target\debug\hello_cargo.exe on Windows), which you can run with this command:
+
This should have created an executable file in target/debug/hello_cargo (or
+target\debug\hello_cargo.exe on Windows), which you can run with this command:
$ ./target/debug/hello_cargo # or .\target\debug\hello_cargo.exe on Windows
Hello, world!
Bam! If all goes well, Hello, world! should print to the terminal once more.
Running cargo build for the first time also causes Cargo to create a new file
-at the top level called Cargo.lock, which looks like this:
-
Filename: Cargo.lock
+at the top level called Cargo.lock, which looks like this:
+
Filename: Cargo.lock
[root]
name = "hello_cargo"
version = "0.1.0"
-
Cargo uses the Cargo.lock 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.
+
Cargo uses the Cargo.lock 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.
We just built a project with cargo build and ran it with
./target/debug/hello_cargo, but we can also use cargo run to compile
and then run:
@@ -409,21 +409,21 @@ Hello, world!
Instead of using rustc, build a project using cargo build (or build and
run it in one step with cargo run)
Instead of the result of the build being put in the same directory as our
-code, Cargo will put it in the target/debug directory.
+code, Cargo will put it in the target/debug directory.
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.
Building for Release
When your project is finally ready for release, you can use cargo build --release to compile your project with optimizations. This will create an
-executable in target/release instead of target/debug. These optimizations
+executable in target/release instead of target/debug. 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 cargo build --release and benchmark with
-the executable in target/release.
+the executable in target/release.
Cargo as Convention
With simple projects, Cargo doesn't provide a whole lot of value over just
using rustc, but it will prove its worth as you continue. With complex
@@ -463,7 +463,7 @@ as the first argument. The --bin flag tells Cargo to make a binary
similar to the one in Chapter 1. The second command changes to the new
project’s directory.
Look at the generated Cargo.toml file:
-
Filename: Cargo.toml
+
Filename: Cargo.toml
[package]
name = "guessing_game"
version = "0.1.0"
@@ -475,7 +475,7 @@ authors = ["Your Name <you@example.com>"]
correct, fix that in the file and save it again.
As you saw in Chapter 1, cargo new generates a “Hello, world!” program for
you. Check out the src/main.rs file:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
println!("Hello, world!");
}
@@ -495,7 +495,8 @@ before moving on to the next one.
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 src/main.rs.
-Listing 2-1: Code to get a guess from the user and print it out
-
+
+
Listing 2-1: Code to get a guess from the user and print it out
+
+
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
io (input/output) library from the standard library (which is known as std):
@@ -690,7 +692,7 @@ code that uses rand, we need to modify the Cargo.toml file
rand crate as a dependency. Open that file now and add the following line to
the bottom beneath the [dependencies] section header that Cargo created for
you:
-
Filename: Cargo.toml
+
Filename: Cargo.toml
[dependencies]
rand = "0.3.14"
@@ -706,6 +708,7 @@ for ^0.3.14, which means “any version that has a public API compa
version 0.3.14.”
Now, without changing any of the code, let’s build the project, as shown in
Listing 2-2:
-Listing 2-3: Code changes needed in order to generate a random number
-
+
+
Listing 2-3: Code changes needed in order to generate a random number
+
+
We’re adding a extern crate rand; line to the top that lets Rust know we’ll be
using that external dependency. This also does the equivalent of calling use rand, so now we can call anything in the rand crate by prefixing it with
rand::.
@@ -867,7 +873,8 @@ You guessed: 5
Comparing the Guess to the Secret Number
Now that we have user input and a random number, we can compare them. That
step is shown in Listing 2-4:
-Listing 2-4: Handling the possible return values of comparing two numbers
-
+
+
Listing 2-4: Handling the possible return values of comparing two numbers
+
+
The first new bit here is another use, bringing a type called
std::cmp::Ordering into scope from the standard library. Ordering is
another enum, like Result, but the variants for Ordering are Less,
@@ -965,7 +973,7 @@ not compare a string and a number type.
Ultimately, we want to convert the String 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 main function body:
-
Filename: src/main.rs
+
Filename: src/main.rs
extern crate rand;
use std::io;
@@ -1058,7 +1066,7 @@ Let’s change that by adding a loop!
Allowing Multiple Guesses with Looping
The loop keyword gives us an infinite loop. Add that now to give users more
chances at guessing the number:
-
Filename: src/main.rs
+
Filename: src/main.rs
extern crate rand;
use std::io;
@@ -1131,7 +1139,7 @@ However, this is suboptimal to say the least. We want the game to automatically
stop when the correct number is guessed.
Quitting After a Correct Guess
Let’s program the game to quit when the user wins by adding a break:
-
Filename: src/main.rs
+
Filename: src/main.rs
extern crate rand;
use std::io;
@@ -1227,7 +1235,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 println! that outputs the
secret number. Listing 2-5 shows the final code:
-
-Listing 2-5: Complete code of the guessing game
-
+
+
Listing 2-5: Complete code of the guessing game
+
+
Summary
At this point, you’ve successfully built the guessing game! Congratulations!
This project was a hands-on way to introduce you to many new Rust concepts:
@@ -1287,6 +1297,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.
+
Keywords
The Rust language has a set of keywords that have been reserved for use by
the language only, much like other languages do. Keep in mind that you cannot
@@ -1295,6 +1306,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.
+
Variables and Mutability
As mentioned in Chapter 2, by default variables are immutable. This is one of
@@ -1307,7 +1319,7 @@ you can’t change that value. To illustrate, let’s generate a new project cal
variables in your projects directory by using cargo new --bin variables.
Then, in your new variables directory, open src/main.rs and replace its
code with the following:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
let x = 5;
println!("The value of x is: {}", x);
@@ -1351,7 +1363,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.
For example, change src/main.rs to the following:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
let mut x = 5;
println!("The value of x is: {}", x);
@@ -1411,7 +1423,7 @@ variables with the same name as a previous variables, and the new variable
shadowed 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 let keyword as follows:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
let x = 5;
@@ -1503,9 +1515,10 @@ that the value it’s associated with should be a signed integer (hence the u 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, i32) can be used to declare the type of an integer value.
-
-Table 3-1: Integer Types in Rust
-
+
+
+
Table 3-1: Integer Types in Rust
+
Length
Signed
Unsigned
8-bit
i8
u8
16-bit
i16
u16
@@ -1513,6 +1526,7 @@ Table 3-1: Integer Types in Rust
64-bit
i64
u64
arch
isize
usize
+
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
@@ -1534,9 +1548,10 @@ if you’re on a 32-bit architecture.
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
57u8, and _ as a visual separator, such as 1_000.
-
-Table 3-2: Integer Literals in Rust
-
+
+
+
Table 3-2: Integer Literals in Rust
+
Number literals
Example
Decimal
98_222
Hex
0xff
@@ -1544,6 +1559,7 @@ Table 3-2: Integer Literals in Rust
Binary
0b1111_0000
Byte (u8 only)
b'A'
+
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 i32: it’s
generally the fastest, even on 64-bit systems. The primary situation in which
@@ -1559,7 +1575,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.
Here’s an example that shows floating-point numbers in action:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
let x = 2.0; // f64
@@ -1572,7 +1588,7 @@ your situation.
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 let statement:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
// addition
let sum = 5 + 10;
@@ -1597,7 +1613,7 @@ list of all operators that Rust provides.
As in most other programming languages, a boolean type in Rust has two possible
values: true and false. The boolean type in Rust is specified using bool.
For example:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
let t = true;
@@ -1611,7 +1627,7 @@ section.
So far we’ve only worked with numbers, but Rust supports letters too. Rust’s
char type is the language’s most primitive alphabetic type, and the following
code shows one way to use it:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
let c = 'z';
let z = 'ℤ';
@@ -1636,7 +1652,7 @@ a variety of types into one compound type.
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:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
let tup: (i32, f64, u8) = (500, 6.4, 1);
}
@@ -1644,7 +1660,7 @@ type annotations in this example:
The variable tup 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:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
let tup = (500, 6.4, 1);
@@ -1661,7 +1677,7 @@ the single tuple into three parts. Finally, the program prints the value of
In addition to destructuring through pattern matching, we can also access a
tuple element directly by using a period (.) followed by the index of the
value we want to access. For example:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
let x: (i32, f64, u8) = (500, 6.4, 1);
@@ -1682,7 +1698,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.
In Rust, the values going into an array are written as a comma-separated list
inside square brackets:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
let a = [1, 2, 3, 4, 5];
}
@@ -1704,7 +1720,7 @@ an array because you know it will always contain 12 items:
Accessing Array Elements
An array is a single chunk of memory allocated on the stack. We can access
elements of an array using indexing, like this:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
let a = [1, 2, 3, 4, 5];
@@ -1718,7 +1734,7 @@ get the value 2 from index [1] in the array.
Invalid Array Element Access
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:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
let a = [1, 2, 3, 4, 5];
@@ -1754,7 +1770,7 @@ declare new functions.
Rust code uses snake case 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:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
println!("Hello, world!");
@@ -1789,7 +1805,7 @@ called and its message is printed.
Function Arguments
Functions can also take arguments. The following rewritten version of
another_function shows what arguments look like in Rust:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
another_function(5);
}
@@ -1814,7 +1830,7 @@ means the compiler almost never needs you to use them elsewhere in the code to
figure out what you mean.
When you want a function to have multiple arguments, separate them inside the
function signature with commas, like this:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
another_function(5, 6);
}
@@ -1853,19 +1869,21 @@ instructions that perform some action and do not return a value. Expressions
evaluate to a resulting value. Let’s look at some examples.
Creating a variable and assigning a value to it with the let keyword is a
statement. In Listing 3-3, let y = 6; is a statement:
-
Filename: src/main.rs
+
+Filename: src/main.rs
fn main() {
let y = 6;
}
-
-Listing 3-3: A `main` function declaration containing one statement.
-
+
+
Listing 3-3: A main function declaration containing one statement.
+
+
Function definitions are also statements; the entire preceding example is a
statement in itself.
Statements do not return values. Therefore, you can’t assign a let statement
to another variable, as the following code tries to do:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
let x = (let y = 6);
}
@@ -1893,7 +1911,7 @@ statements: in Listing 3-3 that had the statement let y = 6;, 6. Calling a function is an
expression. Calling a macro is an expression. The block that we use to create
new scopes, {}, is an expression, for example:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
let x = 5;
@@ -1923,7 +1941,7 @@ values, but we do declare their type after an arrow (->). 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:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn five() -> i32 {
5
}
@@ -1954,7 +1972,7 @@ that line is the same as the following:
return value, but the body of the function is a lonely 5 with no semicolon
because it’s an expression whose value we want to return. Let’s look at another
example:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
let x = plus_one(5);
@@ -1968,7 +1986,7 @@ fn plus_one(x: i32) -> i32 {
Running this code will print The value of x is: 6. What happens if we place a
semicolon at the end of the line containing x + 1, changing it from an
expression to a statement?
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
let x = plus_one(5);
@@ -2014,14 +2032,14 @@ line. For comments that extend beyond a single line, you’ll need to include
// explain what’s going on.
Comments can also be placed at the end of lines containing code:
But you’ll more often see them used in this format, with the comment on a
separate line above the code it's annotating:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
// I’m feeling lucky today.
let lucky_number = 7;
@@ -2040,7 +2058,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.”
Create a new project called branches in your projects directory to explore
the if expression. In the src/main.rs file, input the following:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
let number = 3;
@@ -2084,7 +2102,7 @@ condition was false
It’s also worth noting that the condition in this code must be a bool. To
see what happens if the condition isn’t a bool, try running the following
code:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
let number = 3;
@@ -2114,7 +2132,7 @@ languages such as Ruby and JavaScript. You must be explicit and always provide
if with a boolean as its condition. If we want the if code block to run
only when a number is not equal to 0, for example, we can change the if
expression to the following:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
let number = 3;
@@ -2127,7 +2145,7 @@ expression to the following:
Multiple Conditions with else if
We can have multiple conditions by combining if and else in an else if
expression. For example:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
let number = 6;
@@ -2161,7 +2179,8 @@ Rust branching construct called match for these cases.
Using if in a let statement
Because if is an expression, we can use it on the right side of a let
statement, for instance in Listing 3-4:
-
Filename: src/main.rs
+
+Filename: src/main.rs
fn main() {
let condition = true;
let number = if condition {
@@ -2173,9 +2192,10 @@ statement, for instance in Listing 3-4:
println!("The value of number is: {}", number);
}
-
-Listing 3-4: Assigning the result of an `if` expression to a variable
-
+
+
Listing 3-4: Assigning the result of an if expression to a variable
+
+
The number variable will be bound to a value based on the outcome of the if
expression. Run this code to see what happens:
$ cargo run
@@ -2190,7 +2210,7 @@ values that have the potential to be results from each arm of the ifif arm and the else
arm were i32 integers. But what happens if the types are mismatched, as in
the following example?
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
let condition = true;
@@ -2235,7 +2255,7 @@ experiment with loops, let’s make a new project called loops.
forever or until you explicitly tell it to stop.
As an example, change the src/main.rs file in your loops directory to look
like this:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
loop {
println!("again!");
@@ -2272,7 +2292,7 @@ program, if you’d like.
for it, and it’s called a while loop. The following example uses while: the
program loops three times, counting down each time. Then, after the loop, it
prints another message and exits:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
let mut number = 3;
@@ -2291,7 +2311,8 @@ true, the code runs; otherwise, it exits the loop.
Looping Through a Collection with for
You could use the while construct to loop over the elements of a collection,
such as an array. For example:
-
Filename: src/main.rs
+
+Filename: src/main.rs
fn main() {
let a = [10, 20, 30, 40, 50];
let mut index = 0;
@@ -2303,9 +2324,10 @@ such as an array. For example:
}
}
-
-Listing 3-5: Looping through each element of a collection using a `while` loop
-
+
+
Listing 3-5: Looping through each element of a collection using a while loop
+
+
Here, the code counts up through the elements in the array. It starts at index
0, and then loops until it reaches the final index in the array (that is,
when index < 5 is no longer true). Running this code will print out every
@@ -2328,7 +2350,8 @@ perform the conditional check on every element on every iteration through the
loop.
As a more efficient alternative, you can use a for loop and execute some code
for each item in a collection. A for loop looks like this:
-
Filename: src/main.rs
+
+Filename: src/main.rs
fn main() {
let a = [10, 20, 30, 40, 50];
@@ -2337,9 +2360,10 @@ for each item in a collection. A for loop looks like this:
}
}
-
-Listing 3-6: Looping through each element of a collection using a `for` loop
-
+
+
Listing 3-6: Looping through each element of a collection using a for loop
+
+
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
@@ -2357,7 +2381,7 @@ that generates all numbers in sequence starting from one number and ending
before another number.
Here’s what the countdown would look like using a for loop and another method
we’ve not yet talked about, rev, to reverse the range:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
for number in (1..4).rev() {
println!("{}!", number);
@@ -2601,11 +2625,13 @@ under the covers in Figure 4-1. A String 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.
-
-
-Figure 4-1: Representation in memory of a `String` holding the value `"hello"`
-bound to `s1`
-
+
+
+
+
Figure 4-1: Representation in memory of a String holding the value "hello"
+bound to s1
+
+
The length is how much memory, in bytes, the contents of the String is
currently using. The capacity is the total amount of memory, in bytes, that the
String has gotten from the operating system. The difference between length
@@ -2615,19 +2641,23 @@ the capacity.
copy the pointer, the length, and the capacity that are on the stack. We do not
copy the data on the heap that the String’s pointer refers to. In other
words, it looks like figure 4-2.
-
-
-Figure 4-2: Representation in memory of the variable `s2` that has a copy of
-`s1`’s pointer, length and capacity
-
+
+
+
+
Figure 4-2: Representation in memory of the variable s2 that has a copy of
+s1’s pointer, length and capacity
+
+
And not 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 s2 = s1 could
potentially be very expensive if the data on the heap was large.
-
-
-Figure 4-3: Another possibility for what `s2 = s1` might do, if Rust chose to
-copy heap data as well.
-
+
+
+
+
Figure 4-3: Another possibility for what s2 = s1 might do, if Rust chose to
+copy heap data as well.
+
+
Earlier, we said that when a variable goes out of scope, Rust will
automatically call the drop function and clean up the heap memory for that
variable. But in figure 4-2, we see both data pointers pointing to the same
@@ -2660,10 +2690,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 move. Here we would read this by saying that s1 was moved
into s2. So what actually happens looks like Figure 4-4.
-
-
-Figure 4-4: Representation in memory after `s1` has been invalidated
-
+
+
+
+
Figure 4-4: Representation in memory after s1 has been invalidated
+
+
That solves our problem! With only s2 valid, when it goes out of scope, it
alone will free the memory, and we’re done.
Furthermore, there’s a design choice that’s implied by this: Rust will never
@@ -2725,7 +2757,7 @@ Here’s some of the types that are Copy:
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:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
let s = String::from("hello"); // s comes into scope.
@@ -2756,7 +2788,7 @@ the ownership rules prevent you from doing so.
Return Values and Scope
Returning values can also transfer ownership. Here’s an example with similar
annotations:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
let s1 = gives_ownership(); // gives_ownership moves its return
// value into s1.
@@ -2796,7 +2828,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.
It is possible to return multiple values using a tuple, like this:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
let s1 = String::from("hello");
@@ -2821,7 +2853,7 @@ into calculate_length.
Here is how you would define and use a calculate_length function that takes a
reference to an object as an argument instead of taking ownership of the
argument:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
let s1 = String::from("hello");
@@ -2840,10 +2872,12 @@ function return value is gone. Next, note that we pass &s1 into
String.
These &s are references, and they allow you to refer to some value without
taking ownership of it. Figure 4-5 shows a diagram of this.
-
-
-Figure 4-5: `&String s` pointing at `String s1`
-
+
+
+
+
Figure 4-5: &String s pointing at String s1
+
+
Let’s take a closer look at the function call here:
# fn calculate_length(s: &String) -> usize {
# s.len()
@@ -2871,7 +2905,7 @@ something, you can borrow it from them, and when you’re done, you have to give
it back.
So what happens if we try to modify something we’re borrowing? Try this code
out. Spoiler alert: it doesn’t work!
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
let s = String::from("hello");
@@ -2893,7 +2927,7 @@ fn change(some_string: &String) {
to modify something we have a reference to.
Mutable References
We can fix this error with just a small tweak:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
let mut s = String::from("hello");
@@ -2909,7 +2943,7 @@ reference with &mut s and accept a mutable reference with 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:
-
Filename: src/main.rs
+
Filename: src/main.rs
let mut s = String::from("hello");
let r1 = &mut s;
@@ -2989,7 +3023,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.
Let’s try to create a dangling reference:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
let reference_to_nothing = dangle();
}
@@ -3069,7 +3103,7 @@ returned.
ownership, so this is fine. But what should we return? We don’t really have a
way to talk about part of a string. We could return the index of the end of
the word, though. Let’s try that:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn first_word(s: &String) -> usize {
let bytes = s.as_bytes();
@@ -3114,7 +3148,7 @@ only a meaningful number in the context of the &String. In othe
because it’s a separate value from the String, there’s no guarantee that it
will still be valid in the future. Consider this program that uses this
first_word function:
-
Filename: src/main.rs
+
Filename: src/main.rs
# fn first_word(s: &String) -> usize {
# let bytes = s.as_bytes();
#
@@ -3168,10 +3202,12 @@ slice data structure actually stores the starting position and the length of
the slice. So in the case of let world = &s[6..11];, world would be a slice
that contains a pointer to the 6th byte of s and a length value of 5.
Figure 4-6 shows this in a diagram:
-
-
-Figure 4-6: String slice referring to part of a `String`
-
+
+
+
+
Figure 4-6: String slice referring to part of a String
+
+
With Rust’s .. range syntax, if you want to start at the first index (zero),
you can drop the value before the ... In other words, these are equal:
let s = String::from("hello");
@@ -3199,7 +3235,7 @@ let slice = &s[..];
With this in mind, let’s re-write first_word to return a slice. The type that
signifies “string slice” is written as &str:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn first_word(s: &String) -> &str {
let bytes = s.as_bytes();
@@ -3229,7 +3265,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 first_word will throw a compile time error:
-
Filename: src/main.rs
+
Filename: src/main.rs
fn main() {
let mut s = String::from("hello world");
@@ -3279,7 +3315,7 @@ to use the same function on both