mirror of
https://github.com/rust-lang/book.git
synced 2026-11-30 21:31:17 -06:00
Run the ship-to-nostarch script
To get the fancy quotes and bindings -> variables into the full chapter md files for diffing.
This commit is contained in:
+151
-150
@@ -3,13 +3,13 @@
|
|||||||
|
|
||||||
# Common Programming Concepts in Rust
|
# Common Programming Concepts in Rust
|
||||||
|
|
||||||
Let's first look at concepts that appear in almost every programming language
|
Let’s first look at concepts that appear in almost every programming language
|
||||||
and see how they work in Rust. Many programming languages have much in common
|
and see how they work in Rust. Many programming languages have much in common
|
||||||
at their core. None of the concepts presented in this chapter are unique to
|
at their core. None of the concepts presented in this chapter are unique to
|
||||||
Rust, but we’ll discuss Rust’s particular syntax and conventions concerning
|
Rust, but we’ll discuss Rust’s particular syntax and conventions concerning
|
||||||
these common concepts.
|
these common concepts.
|
||||||
|
|
||||||
Specifically, we’ll be talking about variable bindings, basic types, functions,
|
Specifically, we’ll be talking about variables, basic types, functions,
|
||||||
comments, and control flow. These foundations will be in every Rust
|
comments, and control flow. These foundations will be in every Rust
|
||||||
program, and learning them early will give you a strong core to start from.
|
program, and learning them early will give you a strong core to start from.
|
||||||
|
|
||||||
@@ -26,20 +26,20 @@ keywords in Appendix XX.
|
|||||||
|
|
||||||
PROD: END BOX
|
PROD: END BOX
|
||||||
|
|
||||||
## Variable Bindings and Mutability
|
## Variables and Mutability
|
||||||
|
|
||||||
We mentioned in Chapter 2 that by default, variable bindings are *immutable*.
|
We mentioned in Chapter 2 that by default, variables are *immutable*.
|
||||||
This is one of many nudges in Rust that encourages us to write our code in a
|
This is one of many nudges in Rust that encourages us to write our code in a
|
||||||
way that gets the most of the safety and easy concurrency that Rust has to
|
way that gets the most of the safety and easy concurrency that Rust has to
|
||||||
offer. We still have the option to make our bindings mutable, though. Let's
|
offer. We still have the option to make our variables mutable, though. Let’s
|
||||||
explore how and why Rust encourages us to favor immutability, and why we might
|
explore how and why Rust encourages us to favor immutability, and why we might
|
||||||
want to opt out of that.
|
want to opt out of that.
|
||||||
|
|
||||||
Variable bindings being immutable means that once a value is bound, you can't
|
Variables being immutable means once a value is bound, you can’t
|
||||||
change that value. To illustrate this, let's generate a new project in your
|
change that value. To illustrate this, let’s generate a new project in your
|
||||||
projects directory called *bindings* by using `cargo new --bin bindings`.
|
*projects* directory called `variables` by using `cargo new --bin variables`.
|
||||||
|
|
||||||
Then, in your new *bindings* directory, open *src/main.rs* and replace its code
|
Then, in your new *variables* directory, open *src/main.rs* and replace its code
|
||||||
with the following:
|
with the following:
|
||||||
|
|
||||||
Filename: src/main.rs
|
Filename: src/main.rs
|
||||||
@@ -58,7 +58,7 @@ message, as in this output:
|
|||||||
|
|
||||||
```bash
|
```bash
|
||||||
$ cargo run
|
$ cargo run
|
||||||
Compiling bindings v0.0.1 (file:///projects/bindings)
|
Compiling variables v0.0.1 (file:///projects/variables)
|
||||||
error: re-assignment of immutable variable `x` [--explain E0384]
|
error: re-assignment of immutable variable `x` [--explain E0384]
|
||||||
--> src/main.rs:4:5
|
--> src/main.rs:4:5
|
||||||
4 |> x = 6;
|
4 |> x = 6;
|
||||||
@@ -71,26 +71,27 @@ note: prior assignment occurs here
|
|||||||
|
|
||||||
This is our first example of the compiler helping us find an error in our
|
This is our first example of the compiler helping us find an error in our
|
||||||
program! Compiler errors can be frustrating. Keep in mind that they only mean
|
program! Compiler errors can be frustrating. Keep in mind that they only mean
|
||||||
your program isn't safely doing what you want it to do yet; they do *not* mean
|
your program isn’t safely doing what you want it to do yet; they do *not* mean
|
||||||
that you're not a good programmer! Experienced Rustaceans still get compiler
|
that you’re not a good programmer! Experienced Rustaceans still get compiler
|
||||||
errors. The Rust compiler is trying to help your program be the very best.
|
errors. The Rust compiler is trying to help your program be the very best.
|
||||||
|
|
||||||
PROD: START BOX
|
PROD: START BOX
|
||||||
###### Extended Error Explanations
|
|
||||||
|
|
||||||
Now that you've seen a Rust error, let's take a moment to look at one
|
#### Extended Error Explanations
|
||||||
|
|
||||||
|
Now that you’ve seen a Rust error, let’s take a moment to look at one
|
||||||
particularly useful aspect of errors. Rust encourages you to seek further
|
particularly useful aspect of errors. Rust encourages you to seek further
|
||||||
information on the kind of error you've received with output like this:
|
information on the kind of error you’ve received with output like this:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
error: re-assignment of immutable variable `x` [--explain E0384]
|
error: re-assignment of immutable variable `x` [--explain E0384]
|
||||||
```
|
```
|
||||||
|
|
||||||
This tells us that if we pass the `--explain` flag to `rustc` with the provided
|
This tells us that if we pass the `--explain` flag to `rustc` with the
|
||||||
error code, we can see an extended explanation which will try to explain common
|
provided error code, we can see an extended explanation which will try to
|
||||||
causes of and solutions to that kind of error. Not every error has a longer
|
explain common causes of and solutions to that kind of error. Not every error
|
||||||
explanation, but many do. Here’s a portion of the explanation for the `E0384`
|
has a longer explanation, but many do. Here’s a portion of the explanation
|
||||||
error we received:
|
for the `E0384` error we received:
|
||||||
|
|
||||||
````bash
|
````bash
|
||||||
$ rustc --explain E0384
|
$ rustc --explain E0384
|
||||||
@@ -105,30 +106,30 @@ fn main(){
|
|||||||
```
|
```
|
||||||
````
|
````
|
||||||
|
|
||||||
These explanations can really help if you’re stuck on an error, so don't
|
These explanations can really help if you’re stuck on an error, so don’t
|
||||||
hesitate to look up the error code. The compiler is your friend, and it's there
|
hesitate to look up the error code. The compiler is your friend, and it’s
|
||||||
to help.
|
there to help.
|
||||||
|
|
||||||
PROD: END BOX
|
PROD: END BOX
|
||||||
|
|
||||||
The error tells us that the cause of the error is `re-assigment of immutable
|
The error tells us that the cause of the error is `re-assignment of immutable
|
||||||
variable`, because we tried to assign a second value to the immutable `x`
|
variable`, because we tried to assign a second value to the immutable `x`
|
||||||
variable.
|
variable.
|
||||||
|
|
||||||
It's important that we get compile-time errors when we attempt to change a
|
It’s important that we get compile-time errors when we attempt to change a
|
||||||
value that we previously said was immutable because this very situation can
|
value that we previously said was immutable because this very situation can
|
||||||
lead to bugs. If one part of our code operates on an assumption that a value
|
lead to bugs. If one part of our code operates on an assumption that a value
|
||||||
will never change, and another part of our code changes that value, it's
|
will never change, and another part of our code changes that value, it’s
|
||||||
possible that the first part of the code won't do what it was designed to do.
|
possible that the first part of the code won’t do what it was designed to do.
|
||||||
This cause of bugs can be difficult to track down after the fact, especially
|
This cause of bugs can be difficult to track down after the fact, especially
|
||||||
when the second piece of code only changes the value *sometimes*.
|
when the second piece of code only changes the value *sometimes*.
|
||||||
|
|
||||||
In Rust, we can trust that a value we say won't change really won't change,
|
In Rust, we can trust that a value we say won’t change really won’t change,
|
||||||
because the compiler is enforcing that guarantee for us. When reading and
|
because the compiler is enforcing that guarantee for us. When reading and
|
||||||
writing code, we don't have to keep track in our head how and where a value
|
writing code, we don’t have to keep track in our head how and where a value
|
||||||
might change. This can make code easier to reason about.
|
might change. This can make code easier to reason about.
|
||||||
|
|
||||||
Mutability can be really useful, though! Bindings are immutable only by
|
Mutability can be really useful, though! Variables are immutable only by
|
||||||
default; you can make them mutable by adding `mut` in front of the variable
|
default; you can make them mutable by adding `mut` in front of the variable
|
||||||
name. In addition to allowing this value to be changed, it conveys intent to
|
name. In addition to allowing this value to be changed, it conveys intent to
|
||||||
future readers of the code by indicating that other parts of the code will be
|
future readers of the code by indicating that other parts of the code will be
|
||||||
@@ -151,26 +152,26 @@ Running this, we get:
|
|||||||
|
|
||||||
```bash
|
```bash
|
||||||
$ cargo run
|
$ cargo run
|
||||||
Compiling bindings v0.1.0 (file:///projects/bindings)
|
Compiling variables v0.1.0 (file:///projects/variables)
|
||||||
Running `target/debug/bindings`
|
Running `target/debug/variables`
|
||||||
The value of x is: 5
|
The value of x is: 5
|
||||||
The value of x is: 6
|
The value of x is: 6
|
||||||
```
|
```
|
||||||
|
|
||||||
Using `mut`, we are allowed to change the value that `x` binds to from `5` to
|
Using `mut`, we are allowed to change the value that `x` binds to from `5` to
|
||||||
`6`. In some cases you'll want to make a binding mutable because it makes the
|
`6`. In some cases you’ll want to make a variable mutable because it makes the
|
||||||
code easier to understand than an implementation that only uses immutable
|
code easier to understand than an implementation that only uses immutable
|
||||||
bindings. In cases where you're using large data structures, mutating an
|
variables. In cases where you’re using large data structures, mutating an
|
||||||
instance in place may be faster than copying and returning newly allocated
|
instance in place may be faster than copying and returning newly allocated
|
||||||
instances. It all depends on the tradeoffs you want to make in your situation.
|
instances. It all depends on the tradeoffs you want to make in your situation.
|
||||||
|
|
||||||
### Shadowing
|
### Shadowing
|
||||||
|
|
||||||
As we saw in the guessing game tutorial, we can declare new bindings with the
|
As we saw in the guessing game tutorial, we can declare new variables with the
|
||||||
same name as a previous binding, and the new binding *shadows* the previous
|
same name as a previous variable, and the new variable *shadows* the previous
|
||||||
binding. We say that the first binding is *shadowed* by the second, which means
|
variable. We say that the first variable is *shadowed* by the second, which means
|
||||||
that the second binding's value is what you will see when you use the variable.
|
that the second variable’s value is what you will see when you use the variable.
|
||||||
We can shadow a binding by using the same binding's name and repeating the use
|
We can shadow a variable by using the same variable’s name and repeating the use
|
||||||
of the `let` keyword as follows:
|
of the `let` keyword as follows:
|
||||||
|
|
||||||
Filename: src/main.rs
|
Filename: src/main.rs
|
||||||
@@ -195,19 +196,19 @@ you run this, it will output:
|
|||||||
|
|
||||||
```bash
|
```bash
|
||||||
$ cargo run
|
$ cargo run
|
||||||
Compiling bindings v0.1.0 (file:///projects/bindings)
|
Compiling variables v0.1.0 (file:///projects/variables)
|
||||||
Running `target/debug/bindings`
|
Running `target/debug/variables`
|
||||||
The value of x is: 12
|
The value of x is: 12
|
||||||
```
|
```
|
||||||
|
|
||||||
This is different from marking a binding as `mut` because unless we use the
|
This is different from marking a variable as `mut` because unless we use the
|
||||||
`let` keyword again, we'll get a compile-time error if we accidentally try to
|
`let` keyword again, we’ll get a compile-time error if we accidentally try to
|
||||||
reassign to this binding. We can perform a few transformations on a value, but
|
reassign to this variable. We can perform a few transformations on a value, but
|
||||||
have the binding be immutable after those transformations have been completed.
|
have the variable be immutable after those transformations have been completed.
|
||||||
|
|
||||||
The other difference between `mut` and shadowing is that, since we're
|
The other difference between `mut` and shadowing is that, since we’re
|
||||||
effectively creating a new binding when we use the `let` keyword again, we can
|
effectively creating a new variable when we use the `let` keyword again, we can
|
||||||
change the type of the value we're binding to but reuse the same name. For
|
change the type of the value, but reuse the same name. For
|
||||||
example, say we ask a user to show us how many spaces they want between some
|
example, say we ask a user to show us how many spaces they want between some
|
||||||
text by sending us space characters, but we really want to store that as a
|
text by sending us space characters, but we really want to store that as a
|
||||||
number:
|
number:
|
||||||
@@ -217,8 +218,8 @@ let spaces = " ";
|
|||||||
let spaces = spaces.len();
|
let spaces = spaces.len();
|
||||||
```
|
```
|
||||||
|
|
||||||
This is allowed: the first `spaces` binding is a string type, and the second
|
This is allowed: the first `spaces` variable is a string type, and the second
|
||||||
`spaces` binding, which is a brand new binding that happens to have the same
|
`spaces` variable, which is a brand new variable that happens to have the same
|
||||||
name as the first one, is a number type. Shadowing thus saves us from having to
|
name as the first one, is a number type. Shadowing thus saves us from having to
|
||||||
come up with different names like `spaces_str` and `spaces_num`; we can reuse
|
come up with different names like `spaces_str` and `spaces_num`; we can reuse
|
||||||
the simpler `spaces` name. If we try to use `mut` for this, however, like this:
|
the simpler `spaces` name. If we try to use `mut` for this, however, like this:
|
||||||
@@ -229,7 +230,7 @@ spaces = spaces.len();
|
|||||||
```
|
```
|
||||||
|
|
||||||
We will get a compile-time error because we are not allowed to mutate a
|
We will get a compile-time error because we are not allowed to mutate a
|
||||||
binding's type:
|
variable’s type:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
error: mismatched types [--explain E0308]
|
error: mismatched types [--explain E0308]
|
||||||
@@ -243,18 +244,18 @@ note: found type `usize`
|
|||||||
error: aborting due to previous error
|
error: aborting due to previous error
|
||||||
```
|
```
|
||||||
|
|
||||||
Now that we've explored how variable bindings work, let's look at some more
|
Now that we’ve explored how variables work, let’s look at some more
|
||||||
data types of values that we can bind variables to.
|
data types they can have.
|
||||||
|
|
||||||
## Data Types
|
## Data Types
|
||||||
|
|
||||||
Every value in Rust is of a certain *type*, which tells Rust what kind of data
|
Every value in Rust is of a certain *type*, which tells Rust what kind of data
|
||||||
is being given so it knows how to work with that data. In this section, we'll
|
is being given so it knows how to work with that data. In this section, we’ll
|
||||||
look at a number of types built into the language itself split into two subsets:
|
look at a number of types built into the language itself. We split the types
|
||||||
scalar and compound.
|
into two subsets: scalar and compound.
|
||||||
|
|
||||||
Something to keep in mind throughout this section: Rust is a *statically typed*
|
Something to keep in mind throughout this section: Rust is a *statically typed*
|
||||||
language, which means that it must know the types of all bindings at compile
|
language, which means that it must know the types of all variables at compile
|
||||||
time. The compiler can usually infer what type we want to use based on the
|
time. The compiler can usually infer what type we want to use based on the
|
||||||
value and how we use it. In cases when many types are possible, such as when we
|
value and how we use it. In cases when many types are possible, such as when we
|
||||||
converted a `String` to a numeric type using `parse` in Chapter 2, we must
|
converted a `String` to a numeric type using `parse` in Chapter 2, we must
|
||||||
@@ -264,7 +265,7 @@ add a type annotation, like this:
|
|||||||
let guess: u32 = "42".parse().unwrap();
|
let guess: u32 = "42".parse().unwrap();
|
||||||
```
|
```
|
||||||
|
|
||||||
If we don't put the type annotation here, Rust will give us this error that
|
If we don’t put the type annotation here, Rust will give us this error that
|
||||||
means the compiler needs more information from us to know which possible type
|
means the compiler needs more information from us to know which possible type
|
||||||
we want:
|
we want:
|
||||||
|
|
||||||
@@ -283,14 +284,14 @@ You will see some type annotations as we discuss the various data types.
|
|||||||
|
|
||||||
A *scalar* type represents a single value. There are four primary scalar
|
A *scalar* type represents a single value. There are four primary scalar
|
||||||
types in Rust: integers, floating point numbers, booleans, and characters.
|
types in Rust: integers, floating point numbers, booleans, and characters.
|
||||||
You'll likely recognize these from other programming languages, but let's jump
|
You’ll likely recognize these from other programming languages, but let’s jump
|
||||||
into how they work in Rust.
|
into how they work in Rust.
|
||||||
|
|
||||||
#### Integer Types
|
#### Integer Types
|
||||||
|
|
||||||
An *integer* is a number without a fractional component. We've used one integer
|
An *integer* is a number without a fractional component. We’ve used one integer
|
||||||
type already in this chapter, the `i32` type. This type declaration indicates
|
type already in this chapter, the `i32` type. This type declaration indicates
|
||||||
that the value it's associated with should be a signed integer (hence the `i`,
|
that the value it’s associated with should be a signed integer (hence the `i`,
|
||||||
as opposed to a `u` for unsigned) for a 32-bit system. There are a number of
|
as opposed to a `u` for unsigned) for a 32-bit system. There are a number of
|
||||||
built-in integer types in Rust, shown in Table 3-1.
|
built-in integer types in Rust, shown in Table 3-1.
|
||||||
|
|
||||||
@@ -310,11 +311,11 @@ Each variant can be either signed or unsigned and has an explicit size. Signed
|
|||||||
and unsigned merely refers to whether it is possible for the number to be
|
and unsigned merely refers to whether it is possible for the number to be
|
||||||
either negative or positive; in other words, whether the number needs to have a
|
either negative or positive; in other words, whether the number needs to have a
|
||||||
sign with it (signed), or whether it will only ever be positive and can
|
sign with it (signed), or whether it will only ever be positive and can
|
||||||
therefore be represented without a sign (unsigned). It's like writing numbers
|
therefore be represented without a sign (unsigned). It’s like writing numbers
|
||||||
on paper: when the sign matters, a number is shown with a plus sign or minus
|
on paper: when the sign matters, a number is shown with a plus sign or minus
|
||||||
sign, but when it's safe to assume the number is positive, it's shown with no
|
sign, but when it’s safe to assume the number is positive, it’s shown with no
|
||||||
sign. Signed numbers are stored using two’s complement representation (if
|
sign. Signed numbers are stored using two’s complement representation (if
|
||||||
you're unsure what this is you can search for it online; an explanation is
|
you’re unsure what this is you can search for it online; an explanation is
|
||||||
outside the scope of this text).
|
outside the scope of this text).
|
||||||
|
|
||||||
Each signed variant can store numbers from -(2<sup>n - 1</sup>) to 2<sup>n -
|
Each signed variant can store numbers from -(2<sup>n - 1</sup>) to 2<sup>n -
|
||||||
@@ -324,7 +325,7 @@ to 127. Unsigned variants can store numbers from 0 to 2<sup>n</sup> - 1, so a
|
|||||||
`u8` can store from 0 to 2<sup>8</sup> - 1, which equals 0 to 255.
|
`u8` can store from 0 to 2<sup>8</sup> - 1, which equals 0 to 255.
|
||||||
|
|
||||||
Finally, the `isize` and `usize` types depend on the kind of computer your
|
Finally, the `isize` and `usize` types depend on the kind of computer your
|
||||||
program is running on: 64-bits if you're on a 64-bit architecture, and 32-bits
|
program is running on: 64-bits if you’re on a 64-bit architecture, and 32-bits
|
||||||
if you’re on a 32-bit architecture.
|
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
|
You can write integer literals in any of the forms shown in Table 3-2. Note that
|
||||||
@@ -341,15 +342,15 @@ all number literals except for the byte literal allow a type suffix, such as
|
|||||||
|
|
||||||
*Table 3-2: Integer literals in Rust.*
|
*Table 3-2: Integer literals in Rust.*
|
||||||
|
|
||||||
So how do you know which type of integer to use? If you're unsure, Rust's
|
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
|
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
|
generally the fastest, even on 64-bit systems. The primary situation in which
|
||||||
you'd use `isize` or `usize` is when indexing some sort of collection.
|
you’d use `isize` or `usize` is when indexing some sort of collection.
|
||||||
|
|
||||||
#### Floating-Point Types
|
#### Floating-Point Types
|
||||||
|
|
||||||
Rust also has two primitive types for *floating-point numbers*, which are
|
Rust also has two primitive types for *floating-point numbers*, which are
|
||||||
numbers with decimal points. Rust's floating-point types are `f32` and `f64`,
|
numbers with decimal points. Rust’s floating-point types are `f32` and `f64`,
|
||||||
which are 32 bits and 64 bits in size, respectively. The default type is `f64`,
|
which are 32 bits and 64 bits in size, respectively. The default type is `f64`,
|
||||||
as it’s roughly the same speed as `f32`, but has a larger precision. It is
|
as it’s roughly the same speed as `f32`, but has a larger precision. It is
|
||||||
possible to use an `f64` on 32 bit systems, but it will be slower than using an
|
possible to use an `f64` on 32 bit systems, but it will be slower than using an
|
||||||
@@ -358,7 +359,7 @@ 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 case. See
|
your code if you suspect floating-point size is a problem in your case. See
|
||||||
Chapter XX for how to run benchmarks.
|
Chapter XX for how to run benchmarks.
|
||||||
|
|
||||||
Here's an example showing floating-point numbers in action:
|
Here’s an example showing floating-point numbers in action:
|
||||||
|
|
||||||
Filename: src/main.rs
|
Filename: src/main.rs
|
||||||
|
|
||||||
@@ -377,7 +378,7 @@ Floating-point numbers are represented according to the IEEE-754 standard. The
|
|||||||
|
|
||||||
Rust supports the usual basic mathematic operations you’d expect for all of
|
Rust supports the usual basic mathematic operations you’d expect for all of
|
||||||
these number types: addition, subtraction, multiplication, division, and
|
these number types: addition, subtraction, multiplication, division, and
|
||||||
modulo. This code shows how you'd use each one in a `let` statement:
|
remainder. This code shows how you’d use each one in a `let` statement:
|
||||||
|
|
||||||
Filename: src/main.rs
|
Filename: src/main.rs
|
||||||
|
|
||||||
@@ -395,13 +396,14 @@ fn main() {
|
|||||||
// division
|
// division
|
||||||
let quotient = 56.7 / 32.2;
|
let quotient = 56.7 / 32.2;
|
||||||
|
|
||||||
// modulo
|
// remainder
|
||||||
let remainder = 43 % 5;
|
let remainder = 43 % 5;
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
Each expression in these statements uses a mathematical operator and evaluates
|
Each expression in these statements uses a mathematical operator and evaluates
|
||||||
to a single value, which is then bound to a variable.
|
to a single value, which is then bound to a variable. Appendix XX contains a
|
||||||
|
list of all operators that Rust provides.
|
||||||
|
|
||||||
#### The Boolean Type
|
#### The Boolean Type
|
||||||
|
|
||||||
@@ -420,13 +422,13 @@ fn main() {
|
|||||||
```
|
```
|
||||||
|
|
||||||
The main way to consume boolean values is through conditionals like an `if`
|
The main way to consume boolean values is through conditionals like an `if`
|
||||||
statement. We’ll cover how `if` statements work in Rust in the "Control Flow"
|
statement. We’ll cover how `if` statements work in Rust in the “Control Flow”
|
||||||
section of this chapter.
|
section of this chapter.
|
||||||
|
|
||||||
#### The Character Type
|
#### The Character Type
|
||||||
|
|
||||||
So far we’ve only worked with numbers, but Rust supports letters too. Rust’s
|
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 this code
|
`char` type is the language’s most primitive alphabetic type, and this code
|
||||||
shows one way to use it:
|
shows one way to use it:
|
||||||
|
|
||||||
Filename: src/main.rs
|
Filename: src/main.rs
|
||||||
@@ -443,9 +445,9 @@ Rust’s `char` represents a Unicode Scalar Value, which means that it can
|
|||||||
represent a lot more than just ASCII. Accented letters, Chinese/Japanese/Korean
|
represent a lot more than just ASCII. Accented letters, Chinese/Japanese/Korean
|
||||||
ideographs, emoji, and zero width spaces are all valid `char`s in Rust. Unicode
|
ideographs, emoji, and zero width spaces are all valid `char`s in Rust. Unicode
|
||||||
Scalar Values range from `U+0000` to `U+D7FF` and `U+E000` to `U+10FFFF`
|
Scalar Values range from `U+0000` to `U+D7FF` and `U+E000` to `U+10FFFF`
|
||||||
inclusive. A "character" isn’t really a concept in Unicode, however, so your
|
inclusive. A “character” isn’t really a concept in Unicode, however, so your
|
||||||
human intuition for what a "character" is may not match up with what a `char`
|
human intuition for what a “character” is may not match up with what a `char`
|
||||||
is in Rust. We'll discuss this in detail in the Strings section of Chapter 8.
|
is in Rust. We’ll discuss this in detail in the Strings section of Chapter 8.
|
||||||
|
|
||||||
### Compound Types
|
### Compound Types
|
||||||
|
|
||||||
@@ -459,7 +461,7 @@ distinct types into one compound type.
|
|||||||
|
|
||||||
We create a tuple by writing a comma-separated list of values inside
|
We create a tuple by writing a comma-separated list of values inside
|
||||||
parentheses. Each position in the tuple has a distinct type, and the types of
|
parentheses. Each position in the tuple has a distinct type, and the types of
|
||||||
the different values in the tuple do not have to be the same. We've added
|
the different values in the tuple do not have to be the same. We’ve added
|
||||||
optional type annotations in this example:
|
optional type annotations in this example:
|
||||||
|
|
||||||
Filename: src/main.rs
|
Filename: src/main.rs
|
||||||
@@ -470,10 +472,9 @@ fn main() {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
Note that the single name `tup` binds to the entire tuple, emphasizing the fact
|
The variable `tup` binds to the entire tuple, since a tuple is considered a
|
||||||
that a tuple is considered a single compound element. To get the individual
|
single compound element. To get the individual values out of a tuple, we can
|
||||||
values out of a tuple, we can use pattern matching to destructure a tuple
|
use pattern matching to destructure a tuple value, like this:
|
||||||
value, like this:
|
|
||||||
|
|
||||||
Filename: src/main.rs
|
Filename: src/main.rs
|
||||||
|
|
||||||
@@ -487,9 +488,9 @@ fn main() {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
In this program, we first create a tuple and bind it to the name `tup`. We then
|
In this program, we first create a tuple and bind it to the variable `tup`. We
|
||||||
use a pattern with `let` to take `tup` and turn it into three separate
|
then use a pattern with `let` to take `tup` and turn it into three separate
|
||||||
bindings, `x`, `y`, and `z`. This is called *destructuring*, because it breaks
|
variables, `x`, `y`, and `z`. This is called *destructuring*, because it breaks
|
||||||
the single tuple into three parts. Finally, we print the value of `y`, which is
|
the single tuple into three parts. Finally, we print the value of `y`, which is
|
||||||
`6.4`.
|
`6.4`.
|
||||||
|
|
||||||
@@ -513,13 +514,13 @@ fn main() {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
This program creates a tuple, `x`, and then makes new bindings to each element
|
This program creates a tuple, `x`, and then makes new variables for each element
|
||||||
by using their index. As with most programming languages, the first index in a
|
by using their index. As with most programming languages, the first index in a
|
||||||
tuple is 0.
|
tuple is 0.
|
||||||
|
|
||||||
### Arrays
|
### Arrays
|
||||||
|
|
||||||
Another way to bind a name to a collection of multiple values is with an
|
Another way to have a collection of multiple values is with an
|
||||||
*array*. Unlike a tuple, every element of an array must have the same type.
|
*array*. Unlike a tuple, every element of an array must have the same type.
|
||||||
Arrays in Rust are different than arrays in some other languages because arrays
|
Arrays in Rust are 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 have a fixed length: once declared, they cannot grow or shrink in size.
|
||||||
@@ -536,14 +537,14 @@ fn main() {
|
|||||||
```
|
```
|
||||||
|
|
||||||
While arrays can be useful since they are a primitive type so using them can be
|
While arrays can be useful since they are a primitive type so using them can be
|
||||||
very fast, they aren't as flexible as the vector type. The vector type is a
|
very fast, they aren’t as flexible as the vector type. The vector type is a
|
||||||
similar collection type provided by the standard library that *is* allowed to
|
similar collection type provided by the standard library that *is* allowed to
|
||||||
grow or shrink in size. If you're unsure whether to use an array or a vector,
|
grow or shrink in size. If you’re unsure whether to use an array or a vector,
|
||||||
you should probably go with a vector, and we'll discuss them in more detail in
|
you should probably go with a vector, and we’ll discuss them in more detail in
|
||||||
Chapter 8.
|
Chapter 8.
|
||||||
|
|
||||||
An example of when we might want to use an array is storing the months of the
|
An example of when we might want to use an array is storing the months of the
|
||||||
year. It's very unlikely that our program will need to add or remove months, so
|
year. It’s very unlikely that our program will need to add or remove months, so
|
||||||
we can use an array since we know we will always have 12 items:
|
we can use an array since we know we will always have 12 items:
|
||||||
|
|
||||||
```rust
|
```rust
|
||||||
@@ -567,8 +568,8 @@ fn main() {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
In this example, the binding named `first` will get the value `1`, since that
|
In this example, the variable named `first` will get the value `1`, since that
|
||||||
is the value at index `[0]` in the array. The binding named `second` will get
|
is the value at index `[0]` in the array. The variable named `second` will get
|
||||||
the value `2` from index `[1]` in the array.
|
the value `2` from index `[1]` in the array.
|
||||||
|
|
||||||
#### Invalid Array Element Access
|
#### Invalid Array Element Access
|
||||||
@@ -601,28 +602,28 @@ error: Process didn't exit successfully: `target/debug/arrays` (exit code: 101)
|
|||||||
```
|
```
|
||||||
|
|
||||||
We can see that the compilation did not give us any errors, but we got a
|
We can see that the compilation did not give us any errors, but we got a
|
||||||
*runtime* error and our program didn't exit successfully. When we attempt to
|
*runtime* error and our program didn’t exit successfully. When we attempt to
|
||||||
access an element using indexing, Rust will check that the index we've
|
access an element using indexing, Rust will check that the index we’ve
|
||||||
specified is less than the array length. If the index is greater than the
|
specified is less than the array length. If the index is greater than the
|
||||||
length, it will "panic", which is what it's called when a Rust program exits
|
length, it will *panic*, which is what it’s called when a Rust program exits
|
||||||
with an error.
|
with an error.
|
||||||
|
|
||||||
This is our first example of Rust’s safety principles in action. In many
|
This is our first example of Rust’s safety principles in action. In many
|
||||||
low-level languages, this kind of check is not done, and when you provide an
|
low-level languages, this kind of check is not done, and when you provide an
|
||||||
incorrect index, invalid memory can be accessed. Rust protects us against this
|
incorrect index, invalid memory can be accessed. Rust protects us against this
|
||||||
kind of error by immediately exiting instead of allowing the memory access and
|
kind of error by immediately exiting instead of allowing the memory access and
|
||||||
continuing. We'll discuss more of Rust’s error handling in Chapter XX.
|
continuing. We’ll discuss more of Rust’s error handling in Chapter XX.
|
||||||
|
|
||||||
## How Functions Work
|
## How Functions Work
|
||||||
|
|
||||||
Functions are pervasive in Rust code. We’ve already seen one of the most
|
Functions are pervasive in Rust code. We’ve already seen one of the most
|
||||||
important functions in the language: the `main` function that’s the entry
|
important functions in the language: the `main` function that’s the entry
|
||||||
point of many programs. We've also seen the `fn` keyword, which allows us to
|
point of many programs. We’ve also seen the `fn` keyword, which allows us to
|
||||||
declare new functions.
|
declare new functions.
|
||||||
|
|
||||||
Rust code uses *snake case* as the conventional style for function and variable
|
Rust code uses *snake case* as the conventional style for function and variable
|
||||||
names. In snake case, all letters are lower case, and there are underscores
|
names. In snake case, all letters are lower case, and there are underscores
|
||||||
separating words. Here's a program containing an example function definition:
|
separating words. Here’s a program containing an example function definition:
|
||||||
|
|
||||||
Filename: src/main.rs
|
Filename: src/main.rs
|
||||||
|
|
||||||
@@ -723,7 +724,7 @@ type, but they just happen to be in this example. Our function then prints out
|
|||||||
the values of both of its arguments.
|
the values of both of its arguments.
|
||||||
|
|
||||||
Let’s try out this code. Replace the program currently in your `function`
|
Let’s try out this code. Replace the program currently in your `function`
|
||||||
project's `main.rs` file with the example above, and run it as follows:
|
project’s `main.rs` file with the example above, and run it as follows:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
$ cargo run
|
$ cargo run
|
||||||
@@ -739,20 +740,20 @@ the two strings are printed with these values.
|
|||||||
### Function Bodies
|
### Function Bodies
|
||||||
|
|
||||||
Function bodies are made up of a series of statements optionally ending in an
|
Function bodies are made up of a series of statements optionally ending in an
|
||||||
expression. So far, we've only seen functions without an ending expression, but
|
expression. So far, we’ve only seen functions without an ending expression, but
|
||||||
we have seen expressions as parts of statements. Since Rust is an
|
we have seen expressions as parts of statements. Since Rust is an
|
||||||
expression-based language, this is an important distinction to understand.
|
expression-based language, this is an important distinction to understand.
|
||||||
Other languages don't have the same distinctions, so let's look at what
|
Other languages don’t have the same distinctions, so let’s look at what
|
||||||
statements and expressions are and how their differences affect the bodies of
|
statements and expressions are and how their differences affect the bodies of
|
||||||
functions.
|
functions.
|
||||||
|
|
||||||
#### Statements and Expressions
|
#### Statements and Expressions
|
||||||
|
|
||||||
We've already been using both statements and expressions. *Statements* are
|
We’ve already been using both statements and expressions. *Statements* are
|
||||||
instructions that perform some action and do not return a value. *Expressions*
|
instructions that perform some action and do not return a value. *Expressions*
|
||||||
evaluate to a resulting value. Let's look at some examples.
|
evaluate to a resulting value. Let’s look at some examples.
|
||||||
|
|
||||||
Creating a variable binding and assigning a value to it with the `let` keyword
|
Creating a variable and assigning a value to it with the `let` keyword
|
||||||
is a statement. In this example, `let y = 6;` is a statement:
|
is a statement. In this example, `let y = 6;` is a statement:
|
||||||
|
|
||||||
Filename: src/main.rs
|
Filename: src/main.rs
|
||||||
@@ -767,7 +768,7 @@ Function definitions are also statements; the entire previous example is a
|
|||||||
statement in itself.
|
statement in itself.
|
||||||
|
|
||||||
Statements do not return values themselves. Therefore, you can’t assign a `let`
|
Statements do not return values themselves. Therefore, you can’t assign a `let`
|
||||||
binding to another binding, as this code tries to do:
|
statement to another variable, as this code tries to do:
|
||||||
|
|
||||||
Filename: src/main.rs
|
Filename: src/main.rs
|
||||||
|
|
||||||
@@ -792,7 +793,7 @@ error: aborting due to previous error
|
|||||||
error: Could not compile `functions`.
|
error: Could not compile `functions`.
|
||||||
```
|
```
|
||||||
|
|
||||||
The `let y = 6` statement does not return a value, so there isn't anything for
|
The `let y = 6` statement does not return a value, so there isn’t anything for
|
||||||
`x` to bind to. This is different than in other languages like C and Ruby where
|
`x` to bind to. This is different than in other languages like C and Ruby where
|
||||||
the assignment returns the value of the assignment. In those languages, we can
|
the assignment returns the value of the assignment. In those languages, we can
|
||||||
write `x = y = 6` and have both `x` and `y` have the value `6`; that is not the
|
write `x = y = 6` and have both `x` and `y` have the value `6`; that is not the
|
||||||
@@ -828,7 +829,7 @@ fn main() {
|
|||||||
```
|
```
|
||||||
<!-- If we use wingding numbers to call out code, we might delete the
|
<!-- If we use wingding numbers to call out code, we might delete the
|
||||||
repetition here and just use those numbers--that can help the flow of the text.
|
repetition here and just use those numbers--that can help the flow of the text.
|
||||||
I'm flagging this as a reminder for when we transfer to libreoffice -->
|
I’m flagging this as a reminder for when we transfer to libreoffice -->
|
||||||
|
|
||||||
The expression:
|
The expression:
|
||||||
|
|
||||||
@@ -843,7 +844,7 @@ is a block that, in this case, evaluates to `4`, and then gets bound to
|
|||||||
`y` as part of the `let` statement.
|
`y` as part of the `let` statement.
|
||||||
|
|
||||||
Note that the line containing `x + 1` does not have a semicolon at the end,
|
Note that the line containing `x + 1` does not have a semicolon at the end,
|
||||||
unlike most of the lines we've seen up until now. This is the most important
|
unlike most of the lines we’ve seen up until now. This is the most important
|
||||||
distinction between expressions and statements to remember: statements end in
|
distinction between expressions and statements to remember: statements end in
|
||||||
semicolons while expressions do not. If you add a semicolon to the end of an
|
semicolons while expressions do not. If you add a semicolon to the end of an
|
||||||
expression, that will turn it into a statement, which will then not return a
|
expression, that will turn it into a statement, which will then not return a
|
||||||
@@ -853,8 +854,8 @@ value. Keep this in mind as we explore function return values and expressions.
|
|||||||
|
|
||||||
Functions can return values back to the code that calls them. We don’t name
|
Functions can return values back to the code that calls them. We don’t name
|
||||||
return values, but we do declare their type, after an arrow (`->`). In Rust,
|
return values, but we do declare their type, after an arrow (`->`). In Rust,
|
||||||
the "return value of the function” is synonymous with the "value of the final
|
the “return 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
|
expression in the block of the body of a function.” Here’s an example of a
|
||||||
function that returns a value:
|
function that returns a value:
|
||||||
|
|
||||||
Filename: src/main.rs
|
Filename: src/main.rs
|
||||||
@@ -872,8 +873,8 @@ fn main() {
|
|||||||
```
|
```
|
||||||
|
|
||||||
There are no function calls, macros, or even `let` statements in the `five`
|
There are no function calls, macros, or even `let` statements in the `five`
|
||||||
function: just the number `5` by itself. That's a perfectly valid function in
|
function: just the number `5` by itself. That’s a perfectly valid function in
|
||||||
Rust. Note the function's return type is specified, too, as `-> i32`. Try
|
Rust. Note the function’s return type is specified, too, as `-> i32`. Try
|
||||||
running this code, and the output should look like this:
|
running this code, and the output should look like this:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
@@ -883,10 +884,10 @@ $ cargo run
|
|||||||
The value of x is: 5
|
The value of x is: 5
|
||||||
```
|
```
|
||||||
|
|
||||||
The `5` in `five` is the function's return value, which is why the return type
|
The `5` in `five` is the function’s return value, which is why the return type
|
||||||
is `i32`. Let’s examine this in more detail. There are two important bits.
|
is `i32`. Let’s examine this in more detail. There are two important bits.
|
||||||
First, the line `let x = five();` shows us using the return value of a function
|
First, the line `let x = five();` shows us using the return value of a function
|
||||||
to initialize a binding.
|
to initialize a variable.
|
||||||
|
|
||||||
Because the function `five` returns a `5`, that line is the same as saying:
|
Because the function `five` returns a `5`, that line is the same as saying:
|
||||||
|
|
||||||
@@ -897,7 +898,7 @@ let x = 5;
|
|||||||
The second interesting bit is the `five` function itself. It requires no
|
The second interesting bit is the `five` function itself. It requires no
|
||||||
arguments and defines the type of the return value, but the body of the
|
arguments and defines the type of the return value, but the body of the
|
||||||
function is a lonely `5` with no semicolon because it is an expression whose
|
function is a lonely `5` with no semicolon because it is an expression whose
|
||||||
value we want to return. Let's look at another example:
|
value we want to return. Let’s look at another example:
|
||||||
|
|
||||||
Filename: src/main.rs
|
Filename: src/main.rs
|
||||||
|
|
||||||
@@ -949,7 +950,7 @@ error: aborting due to previous error
|
|||||||
error: Could not compile `functions`.
|
error: Could not compile `functions`.
|
||||||
```
|
```
|
||||||
|
|
||||||
The main error message, "not all control paths return a value", reveals the
|
The main error message, “not all control paths return a value”, reveals the
|
||||||
core of the issue with this code. The definition of the function `plus_one`
|
core of the issue with this code. The definition of the function `plus_one`
|
||||||
says that it will return an `i32`, but statements don’t evaluate to a value.
|
says that it will return an `i32`, but statements don’t evaluate to a value.
|
||||||
Therefore, nothing is returned, which contradicts the function definition and
|
Therefore, nothing is returned, which contradicts the function definition and
|
||||||
@@ -970,7 +971,7 @@ Here’s a simple comment:
|
|||||||
```
|
```
|
||||||
|
|
||||||
In Rust, comments must start with two slashes and will last until the end of
|
In Rust, comments must start with two slashes and will last until the end of
|
||||||
the line. For comments that extend beyond a single line, you'll need to
|
the line. For comments that extend beyond a single line, you’ll need to
|
||||||
include `//` on each line, like this:
|
include `//` on each line, like this:
|
||||||
|
|
||||||
```rust
|
```rust
|
||||||
@@ -1013,8 +1014,8 @@ and loops.
|
|||||||
### `if` Expressions
|
### `if` Expressions
|
||||||
|
|
||||||
An `if` expression allows us to branch our code depending on conditions. We
|
An `if` expression allows us to branch our code depending on conditions. We
|
||||||
provide a condition and then say, "If this condition is met, run this
|
provide a condition and then say, “If this condition is met, run this
|
||||||
block of code. If the condition is not met, do not run this block of code."
|
block of code. If the condition is not met, do not run this block of code.”
|
||||||
|
|
||||||
Let’s make a new project to explore `if`, called `branches`. In *src/main.rs*,
|
Let’s make a new project to explore `if`, called `branches`. In *src/main.rs*,
|
||||||
put:
|
put:
|
||||||
@@ -1034,13 +1035,13 @@ fn main() {
|
|||||||
```
|
```
|
||||||
|
|
||||||
All `if` expressions start with the keyword `if`, which is followed by a
|
All `if` expressions start with the keyword `if`, which is followed by a
|
||||||
condition. In this case, our condition is checking if our variable binding
|
condition. In this case, our condition is checking if our variable
|
||||||
`number` has a value that is less than 5. The block of code we want to execute
|
`number` has a value that is less than 5. The block of code we want to execute
|
||||||
if the condition is true goes immediately after the condition, inside curly
|
if the condition is true goes immediately after the condition, inside curly
|
||||||
braces. These blocks are sometimes called *arms*. We can optionally also
|
braces. These blocks are sometimes called *arms*. We can optionally also
|
||||||
include an `else` expression, which we have chosen to do here. This gives the
|
include an `else` expression, which we have chosen to do here. This gives the
|
||||||
program an alternative block of code to execute should the condition evaluate
|
program an alternative block of code to execute should the condition evaluate
|
||||||
to false. If you don't give an `else` expression and the condition is false,
|
to false. If you don’t give an `else` expression and the condition is false,
|
||||||
the program will just skip the `if` block and move on to the next bit of code.
|
the program will just skip the `if` block and move on to the next bit of code.
|
||||||
|
|
||||||
Try running this code, and you should see output like this:
|
Try running this code, and you should see output like this:
|
||||||
@@ -1069,7 +1070,7 @@ condition was false
|
|||||||
```
|
```
|
||||||
|
|
||||||
It’s also worth noting that the condition here *must* be a `bool`. To see what
|
It’s also worth noting that the condition here *must* be a `bool`. To see what
|
||||||
happens if the condition isn't a `bool`, try running this code:
|
happens if the condition isn’t a `bool`, try running this code:
|
||||||
|
|
||||||
Filename: src/main.rs
|
Filename: src/main.rs
|
||||||
|
|
||||||
@@ -1157,18 +1158,18 @@ When this program executes, it will check each `if` expression in turn and
|
|||||||
execute the first body for which the condition holds true. Note that even
|
execute the first body for which the condition holds true. Note that even
|
||||||
though 6 is divisible by 2, we did not see the output `number is divisible by
|
though 6 is divisible by 2, we did not see the output `number is divisible by
|
||||||
2`, nor did we see the `number is not divisible by 4, 3, or 2` text from the
|
2`, nor did we see the `number is not divisible by 4, 3, or 2` text from the
|
||||||
`else` block. That's because Rust will only execute the block for the first
|
`else` block. That’s because Rust will only execute the block for the first
|
||||||
true condition, and once it finds one, it won't even check the rest.
|
true condition, and once it finds one, it won’t even check the rest.
|
||||||
|
|
||||||
Using too many `else if` expressions can clutter your code, so if you find
|
Using too many `else if` expressions can clutter your code, so if you find
|
||||||
yourself with more than one, you may want to look at refactoring your code. In
|
yourself with more than one, you may want to look at refactoring your code. In
|
||||||
Chapter 6, we'll talk about a powerful Rust branching construct called `match`
|
Chapter 6, we’ll talk about a powerful Rust branching construct called `match`
|
||||||
for these cases.
|
for these cases.
|
||||||
|
|
||||||
#### Using `if` in a Binding
|
#### Using `if` in a `let` statement
|
||||||
|
|
||||||
The last detail you need to know about `if` is that it’s an expression. That
|
The last detail you need to know about `if` is that it’s an expression. That
|
||||||
means that we can use it on the right hand side of a `let` binding, for
|
means that we can use it on the right hand side of a `let` statement, for
|
||||||
instance:
|
instance:
|
||||||
|
|
||||||
Filename: src/main.rs
|
Filename: src/main.rs
|
||||||
@@ -1239,14 +1240,14 @@ error: aborting due to previous error
|
|||||||
error: Could not compile `branches`.
|
error: Could not compile `branches`.
|
||||||
```
|
```
|
||||||
|
|
||||||
The expression in the `if` block evaluates to an integer and the expresion in
|
The expression in the `if` block evaluates to an integer and the expression in
|
||||||
the `else` block evaluates to a string. This can’t work, because variable
|
the `else` block evaluates to a string. This can’t work, because variables
|
||||||
bindings must have a single type. Rust needs to know at compile time what type
|
must have a single type. Rust needs to know at compile time what type
|
||||||
the `number` binding is, definitively, so that it can verify at compile time
|
the `number` variable is, definitively, so that it can verify at compile time
|
||||||
that its type is valid everywhere we use `number`. Rust wouldn't be able to do
|
that its type is valid everywhere we use `number`. Rust wouldn’t be able to do
|
||||||
that if the type of `number` was only determined at runtime; the compiler would
|
that if the type of `number` was only determined at runtime; the compiler would
|
||||||
be more complex and be able to make fewer guarantees about our code if it had
|
be more complex and be able to make fewer guarantees about our code if it had
|
||||||
to keep track of multiple hypothetical types for any variable binding.
|
to keep track of multiple hypothetical types for any variable.
|
||||||
|
|
||||||
### Repetition with Loops
|
### Repetition with Loops
|
||||||
|
|
||||||
@@ -1291,7 +1292,7 @@ again!
|
|||||||
^Cagain!
|
^Cagain!
|
||||||
```
|
```
|
||||||
|
|
||||||
That `^C` there is where we hit `control-c`. You may or may not see "again!"
|
That `^C` there is where we hit `control-c`. You may or may not see `again!`
|
||||||
printed after the `^C`, depending on where the code was in the loop when it
|
printed after the `^C`, depending on where the code was in the loop when it
|
||||||
received the signal to halt.
|
received the signal to halt.
|
||||||
|
|
||||||
@@ -1303,14 +1304,14 @@ correctly.
|
|||||||
|
|
||||||
#### Conditional Loops With `while`
|
#### Conditional Loops With `while`
|
||||||
|
|
||||||
It's often useful for a program to have a condition that can be evaluated
|
It’s often useful for a program to have a condition that can be evaluated
|
||||||
within a loop. While the condition is true, the loop runs. When the condition
|
within a loop. While the condition is true, the loop runs. When the condition
|
||||||
ceases to be true, we call `break`, stopping the loop. This could be
|
ceases to be true, we call `break`, stopping the loop. This could be
|
||||||
implemented with a combination of `loop`, `if`, `else`, and `break`; you could
|
implemented with a combination of `loop`, `if`, `else`, and `break`; you could
|
||||||
try that now in a program, if you'd like.
|
try that now in a program, if you’d like.
|
||||||
|
|
||||||
But this pattern is so common that Rust has a more efficient language construct
|
But this pattern is so common that Rust has a more efficient language construct
|
||||||
for it, called a `while` loop. Here's an example using `while`: this program
|
for it, called a `while` loop. Here’s an example using `while`: this program
|
||||||
loops three times, counting down each time. Finally, after the loop, it prints
|
loops three times, counting down each time. Finally, after the loop, it prints
|
||||||
another message, then exits:
|
another message, then exits:
|
||||||
|
|
||||||
@@ -1331,7 +1332,7 @@ fn main() {
|
|||||||
```
|
```
|
||||||
|
|
||||||
This gets rid of a lot of nesting that would be necessary if we used `loop`,
|
This gets rid of a lot of nesting that would be necessary if we used `loop`,
|
||||||
`if`, `else`, and `break`, and it's more clear. While a condition holds, run
|
`if`, `else`, and `break`, and it’s more clear. While a condition holds, run
|
||||||
this code; otherwise, exit the loop.
|
this code; otherwise, exit the loop.
|
||||||
|
|
||||||
#### Looping Through a Collection with `for`
|
#### Looping Through a Collection with `for`
|
||||||
@@ -1354,7 +1355,7 @@ fn main() {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
Here, we're counting up through the elements in the array. We start at index 0,
|
Here, we’re counting up through the elements in the array. We start at index 0,
|
||||||
then loop until we hit the final index of our array (that is, when `index < 5`
|
then loop until we hit the final index of our array (that is, when `index < 5`
|
||||||
is no longer true). Running this will print out every element of the array:
|
is no longer true). Running this will print out every element of the array:
|
||||||
|
|
||||||
@@ -1374,7 +1375,7 @@ will reach a value of `6` at some point, the loop stops executing before trying
|
|||||||
to fetch a sixth value from the array.
|
to fetch a sixth value from the array.
|
||||||
|
|
||||||
This approach is error-prone, though; we could cause our program to panic by
|
This approach is error-prone, though; we could cause our program to panic by
|
||||||
getting the index length incorrect. It's also slow, as the compiler needs to
|
getting the index length incorrect. It’s also slow, as the compiler needs to
|
||||||
perform the conditional check on every element on every iteration through the
|
perform the conditional check on every element on every iteration through the
|
||||||
loop.
|
loop.
|
||||||
|
|
||||||
@@ -1393,8 +1394,8 @@ fn main() {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
If we run this, we'll see the same output as the previous example. Importantly,
|
If we run this, we’ll see the same output as the previous example. Importantly,
|
||||||
though, we've now increased the safety of our code and eliminated the chance of
|
though, we’ve now increased the safety of our code and eliminated the chance of
|
||||||
bugs that might result from going beyond the end of the array or not going far
|
bugs that might result from going beyond the end of the array or not going far
|
||||||
enough and missing some items.
|
enough and missing some items.
|
||||||
|
|
||||||
@@ -1404,7 +1405,7 @@ item from the `a` array but forgot to update the condition to `while index <
|
|||||||
remember to change any other code if we changed the number of values in the
|
remember to change any other code if we changed the number of values in the
|
||||||
array.
|
array.
|
||||||
|
|
||||||
If you're wondering about the `iter` code in this example, keep reading! We
|
If you’re wondering about the `iter` code in this example, keep reading! We
|
||||||
will cover method syntax generally in Chapter XX and iterators specifically in
|
will cover method syntax generally in Chapter XX and iterators specifically in
|
||||||
Chapter XX.
|
Chapter XX.
|
||||||
|
|
||||||
@@ -1415,8 +1416,8 @@ Rustaceans would use a `for` loop. The way to do that would be to use a
|
|||||||
`Range`, which is a type provided by the standard library that generates all
|
`Range`, which is a type provided by the standard library that generates all
|
||||||
numbers in sequence starting from one number and ending before another number.
|
numbers in sequence starting from one number and ending before another number.
|
||||||
|
|
||||||
Here's what the countdown would look like with a for loop, and using another
|
Here’s what the countdown would look like with a for loop, and using another
|
||||||
method we haven't yet talked about, `rev`, to reverse the range:
|
method we haven’t yet talked about, `rev`, to reverse the range:
|
||||||
|
|
||||||
Filename: src/main.rs
|
Filename: src/main.rs
|
||||||
|
|
||||||
@@ -1429,12 +1430,12 @@ fn main() {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
That's a bit nicer, isn't it?
|
That’s a bit nicer, isn’t it?
|
||||||
|
|
||||||
## Summary
|
## Summary
|
||||||
|
|
||||||
You made it! That was a big chapter: we covered variable bindings, scalar and
|
You made it! That was a big chapter: we covered variables, scalar and
|
||||||
compound data types, functions, comments, `if` expressions, and loops! If you'd
|
compound data types, functions, comments, `if` expressions, and loops! If you’d
|
||||||
like to get some practice with the concepts in this chapter, try building
|
like to get some practice with the concepts in this chapter, try building
|
||||||
programs to do things like:
|
programs to do things like:
|
||||||
|
|
||||||
@@ -1443,5 +1444,5 @@ programs to do things like:
|
|||||||
* Print the lyrics to the Christmas carol *The Twelve Days of Christmas*,
|
* Print the lyrics to the Christmas carol *The Twelve Days of Christmas*,
|
||||||
taking advantage of the repetition in the song.
|
taking advantage of the repetition in the song.
|
||||||
|
|
||||||
When you're ready to move on, we'll talk about a concept in Rust that *doesn't*
|
When you’re ready to move on, we’ll talk about a concept in Rust that *doesn’t*
|
||||||
commonly exist in other programming languages: ownership.
|
commonly exist in other programming languages: ownership.
|
||||||
|
|||||||
+120
-122
@@ -3,9 +3,9 @@
|
|||||||
|
|
||||||
# Understanding Ownership
|
# Understanding Ownership
|
||||||
|
|
||||||
Ownership is Rust's most unique feature, and enables Rust to make memory safety
|
Ownership is Rust’s most unique feature, and enables Rust to make memory safety
|
||||||
guarantees without needing a garbage collector. It's therefore important to
|
guarantees without needing a garbage collector. It’s therefore important to
|
||||||
understand how ownership works in Rust. In this chapter we'll talk about
|
understand how ownership works in Rust. In this chapter we’ll talk about
|
||||||
ownership as well as several related features: borrowing, slices, and how Rust
|
ownership as well as several related features: borrowing, slices, and how Rust
|
||||||
lays things out in memory.
|
lays things out in memory.
|
||||||
|
|
||||||
@@ -14,7 +14,7 @@ lays things out in memory.
|
|||||||
Rust’s central feature is *ownership*. It is a feature that is straightforward
|
Rust’s central feature is *ownership*. It is a feature that is straightforward
|
||||||
to explain, but has deep implications for the rest of the language.
|
to explain, but has deep implications for the rest of the language.
|
||||||
|
|
||||||
All programs have to manage the way they use a computer's memory while running.
|
All programs have to manage the way they use a computer’s memory while running.
|
||||||
Some languages have garbage collection, while in others, the programmer has to
|
Some languages have garbage collection, while in others, the programmer has to
|
||||||
explicitly allocate and free the memory. Rust takes a third approach: memory is
|
explicitly allocate and free the memory. Rust takes a third approach: memory is
|
||||||
managed through a system of ownership with a set of rules that the compiler
|
managed through a system of ownership with a set of rules that the compiler
|
||||||
@@ -23,23 +23,23 @@ features.
|
|||||||
|
|
||||||
Since ownership is a new concept for many programmers, it does take
|
Since ownership is a new concept for many programmers, it does take
|
||||||
some time to get used to. There is good news, though: the more experienced you
|
some time to get used to. There is good news, though: the more experienced you
|
||||||
become with Rust and the rules of the ownership system, the more you'll be
|
become with Rust and the rules of the ownership system, the more you’ll be
|
||||||
able to naturally develop code that is both safe and efficient. Keep at it!
|
able to naturally develop code that is both safe and efficient. Keep at it!
|
||||||
|
|
||||||
Once you understand ownership, you have a good foundation for understanding the
|
Once you understand ownership, you have a good foundation for understanding the
|
||||||
features that make Rust unique. In this chapter, we'll learn ownership by going
|
features that make Rust unique. In this chapter, we’ll learn ownership by going
|
||||||
through some examples, focusing on a very common data structure: strings.
|
through some examples, focusing on a very common data structure: strings.
|
||||||
|
|
||||||
PROD: START BOX
|
PROD: START BOX
|
||||||
|
|
||||||
###### The Stack and the Heap
|
#### The Stack and the Heap
|
||||||
|
|
||||||
In many programming languages, we don't have to think about the stack and the
|
In many programming languages, we don’t have to think about the stack and the
|
||||||
heap very often. But in a systems programming language like Rust, whether a
|
heap very often. But in a systems programming language like Rust, whether a
|
||||||
value is on the stack or the heap has more of an effect on how the language
|
value is on the stack or the heap has more of an effect on how the language
|
||||||
behaves and why we have to make certain decisions. We're going to be describing
|
behaves and why we have to make certain decisions. We’re going to be
|
||||||
parts of ownership in relation to the stack and the heap, so here is a brief
|
describing parts of ownership in relation to the stack and the heap, so here
|
||||||
explanation.
|
is a brief explanation.
|
||||||
|
|
||||||
Both the stack and the heap are parts of memory that is available to your code
|
Both the stack and the heap are parts of memory that is available to your code
|
||||||
to use at runtime, but they are structured in different ways. The stack stores
|
to use at runtime, but they are structured in different ways. The stack stores
|
||||||
@@ -47,23 +47,23 @@ values in the order it gets them and removes the values in the opposite order.
|
|||||||
This is referred to as *last in, first out*. Think of a stack of plates: when
|
This is referred to as *last in, first out*. Think of a stack of plates: when
|
||||||
you add more plates, you put them on top of the pile, and when you need a
|
you add more plates, you put them on top of the pile, and when you need a
|
||||||
plate, you take one off the top. Adding or removing plates from the middle or
|
plate, you take one off the top. Adding or removing plates from the middle or
|
||||||
bottom wouldn't work as well! Adding data is called *pushing onto the stack*
|
bottom wouldn’t work as well! Adding data is called *pushing onto the stack*
|
||||||
and removing data is called *popping off the stack*.
|
and removing data is called *popping off the stack*.
|
||||||
|
|
||||||
The stack is fast because of the way it accesses the data: it never has to look
|
The stack is fast because of the way it accesses the data: it never has to
|
||||||
around for a place to put new data or a place to get data from; that place is
|
look around for a place to put new data or a place to get data from; that
|
||||||
always the top. Another property that makes the stack fast is that all data on
|
place is always the top. Another property that makes the stack fast is that
|
||||||
the stack must take up a known, fixed size.
|
all data on the stack must take up a known, fixed size.
|
||||||
|
|
||||||
For data with a size unknown to us at compile time, or a size that might
|
For data with a size unknown to us at compile time, or a size that might
|
||||||
change, we can store data on the heap instead. The heap is less organized: when
|
change, we can store data on the heap instead. The heap is less organized:
|
||||||
we put data on the heap, we ask for some amount of space. The operating system
|
when we put data on the heap, we ask for some amount of space. The operating
|
||||||
finds an empty spot somewhere in the heap that is big enough, marks it as being
|
system finds an empty spot somewhere in the heap that is big enough, marks it
|
||||||
in use, and returns to us a pointer to that location. This process is called
|
as being in use, and returns to us a pointer to that location. This process
|
||||||
*allocating on the heap*, and sometimes we just say "allocating" for short.
|
is called *allocating on the heap*, and sometimes we just say *allocating*
|
||||||
Pushing values onto the stack is not considered allocating. Since the pointer
|
for short. Pushing values onto the stack is not considered allocating. Since
|
||||||
is a known, fixed size, we can store the pointer on the stack, but when we want
|
the pointer is a known, fixed size, we can store the pointer on the stack,
|
||||||
the actual data, we have to follow the pointer.
|
but when we want the actual data, we have to follow the pointer.
|
||||||
|
|
||||||
Think of being seated at a restaurant. When you enter, you say how many people
|
Think of being seated at a restaurant. When you enter, you say how many people
|
||||||
are in your group, and the staff finds an empty table that would fit everyone
|
are in your group, and the staff finds an empty table that would fit everyone
|
||||||
@@ -73,48 +73,48 @@ you have been seated to find you.
|
|||||||
Accessing data in the heap is slower because we have to follow a pointer to
|
Accessing data in the heap is slower because we have to follow a pointer to
|
||||||
get there. Allocating a large amount of space can also take time.
|
get there. Allocating a large amount of space can also take time.
|
||||||
|
|
||||||
When our code calls a function, the values passed into the function (including,
|
When our code calls a function, the values passed into the function
|
||||||
potentially, pointers to data on the heap) and the function's local variables
|
(including, potentially, pointers to data on the heap) and the function’s
|
||||||
get pushed onto the stack. When the function is over, those values get popped
|
local variables get pushed onto the stack. When the function is over, those
|
||||||
off the stack.
|
values get popped off the stack.
|
||||||
|
|
||||||
Keeping track of what parts of code are using what data on the heap, minimizing
|
Keeping track of what parts of code are using what data on the heap,
|
||||||
the amount of duplicate data on the heap, and cleaning up unused data on the
|
minimizing the amount of duplicate data on the heap, and cleaning up unused
|
||||||
heap so that we don't run out of space are all problems that ownership
|
data on the heap so that we don’t run out of space are all problems that
|
||||||
addresses. Once you understand ownership, you won't need to think about the
|
ownership addresses. Once you understand ownership, you won’t need to think
|
||||||
stack and the heap very often, but knowing that managing heap data is why
|
about the stack and the heap very often, but knowing that managing heap data
|
||||||
ownership exists can help explain why it works the way it does.
|
is why ownership exists can help explain why it works the way it does.
|
||||||
|
|
||||||
PROD: END BOX
|
PROD: END BOX
|
||||||
|
|
||||||
### Ownership Rules
|
### Ownership Rules
|
||||||
|
|
||||||
First, let's take a look at the rules. Keep these in mind as we go through the
|
First, let’s take a look at the rules. Keep these in mind as we go through the
|
||||||
examples that will illustrate the rules:
|
examples that will illustrate the rules:
|
||||||
|
|
||||||
> 1. Each value in Rust has a variable binding that’s called its *owner*.
|
1. Each value in Rust has a variable that’s called its *owner*.
|
||||||
> 2. There can only be one owner at a time.
|
2. There can only be one owner at a time.
|
||||||
> 3. When the owner goes out of scope, the value will be dropped.
|
3. When the owner goes out of scope, the value will be dropped.
|
||||||
|
|
||||||
### Variable Binding Scope
|
### Variable Scope
|
||||||
|
|
||||||
We've walked through an example of a Rust program already in the tutorial
|
We’ve walked through an example of a Rust program already in the tutorial
|
||||||
chapter. Now that we’re past basic syntax, we won’t include all of the `fn
|
chapter. Now that we’re past basic syntax, we won’t include all of the `fn
|
||||||
main() {` stuff in examples, so if you’re following along, you will have to put
|
main() {` stuff in examples, so if you’re following along, you will have to put
|
||||||
the following examples inside of a `main` function yourself. This lets our
|
the following examples inside of a `main` function yourself. This lets our
|
||||||
examples be a bit more concise, letting us focus on the actual details rather
|
examples be a bit more concise, letting us focus on the actual details rather
|
||||||
than boilerplate.
|
than boilerplate.
|
||||||
|
|
||||||
As a first example of ownership, we'll look at the *scope* of some variable
|
As a first example of ownership, we’ll look at the *scope* of some variables.
|
||||||
bindings. A scope is the range within a program for which an item is valid.
|
A scope is the range within a program for which an item is valid.
|
||||||
Let's say we have a variable binding that looks like this:
|
Let’s say we have a variable that looks like this:
|
||||||
|
|
||||||
```rust
|
```rust
|
||||||
let s = "hello";
|
let s = "hello";
|
||||||
```
|
```
|
||||||
|
|
||||||
The variable binding `s` refers to a string literal, where the value of the
|
The variable `s` refers to a string literal, where the value of the
|
||||||
string is hard coded into the text of our program. The binding is valid from
|
string is hard coded into the text of our program. The variable is valid from
|
||||||
the point at which it’s declared until the end of the current *scope*. That is:
|
the point at which it’s declared until the end of the current *scope*. That is:
|
||||||
|
|
||||||
```rust
|
```rust
|
||||||
@@ -136,17 +136,17 @@ build on top of this understanding by introducing the `String` type.
|
|||||||
### The `String` Type
|
### The `String` Type
|
||||||
|
|
||||||
In order to illustrate the rules of ownership, we need a data type that is more
|
In order to illustrate the rules of ownership, we need a data type that is more
|
||||||
complex than the ones we covered in Chapter 3. All of the data types we've
|
complex than the ones we covered in Chapter 3. All of the data types we’ve
|
||||||
looked at previously are stored on the stack and popped off the stack when
|
looked at previously are stored on the stack and popped off the stack when
|
||||||
their scope is over, but we want to look at data that is stored on the heap and
|
their scope is over, but we want to look at data that is stored on the heap and
|
||||||
explore how Rust knows when to clean that data up.
|
explore how Rust knows when to clean that data up.
|
||||||
|
|
||||||
We're going to use `String` as the example here and concentrate on the parts of
|
We’re going to use `String` as the example here and concentrate on the parts of
|
||||||
`String` that relate to ownership. These aspects also apply to other complex
|
`String` that relate to ownership. These aspects also apply to other complex
|
||||||
data types provided by the standard library and that you create. We'll go into
|
data types provided by the standard library and that you create. We’ll go into
|
||||||
more depth about `String` specifically in Chapter XX.
|
more depth about `String` specifically in Chapter XX.
|
||||||
|
|
||||||
We've already seen string literals, where a string value is hard-coded into our
|
We’ve already seen string literals, where a string value is hard-coded into our
|
||||||
program. String literals are convenient, but they aren’t always suitable for
|
program. String literals are convenient, but they aren’t always suitable for
|
||||||
every situation you want to use text. For one thing, they’re immutable. For
|
every situation you want to use text. For one thing, they’re immutable. For
|
||||||
another, not every string value can be known when we write our code: what if we
|
another, not every string value can be known when we write our code: what if we
|
||||||
@@ -200,9 +200,9 @@ implementation requests the memory it needs. This is pretty much universal in
|
|||||||
programming languages.
|
programming languages.
|
||||||
|
|
||||||
The second case, however, is different. In languages with a *garbage collector*
|
The second case, however, is different. In languages with a *garbage collector*
|
||||||
(GC), the GC will keep track and clean up memory that isn't being used anymore,
|
(GC), the GC will keep track and clean up memory that isn’t being used anymore,
|
||||||
and we, as the programmer, don’t need to think about it. Without GC, it’s the
|
and we, as the programmer, don’t need to think about it. Without GC, it’s the
|
||||||
programmer's responsibility to identify when memory is no longer being used and
|
programmer’s responsibility to identify when memory is no longer being used and
|
||||||
call code to explicitly return it, just as we did to request it. Doing this
|
call code to explicitly return it, just as we did to request it. Doing this
|
||||||
correctly has historically been a difficult problem in programming. If we
|
correctly has historically been a difficult problem in programming. If we
|
||||||
forget, we will waste memory. If we do it too early, we will have an invalid
|
forget, we will waste memory. If we do it too early, we will have an invalid
|
||||||
@@ -210,7 +210,7 @@ variable. If we do it twice, that’s a bug too. We need to pair exactly one
|
|||||||
`allocate` with exactly one `free`.
|
`allocate` with exactly one `free`.
|
||||||
|
|
||||||
Rust takes a different path: the memory is automatically returned once the
|
Rust takes a different path: the memory is automatically returned once the
|
||||||
binding to it goes out of scope. Here’s a version of our scope example from
|
variable that owns it goes out of scope. Here’s a version of our scope example from
|
||||||
earlier using `String`:
|
earlier using `String`:
|
||||||
|
|
||||||
```rust
|
```rust
|
||||||
@@ -223,25 +223,25 @@ earlier using `String`:
|
|||||||
|
|
||||||
There is a natural point at which we can return the memory our `String` needs
|
There is a natural point at which we can return the memory our `String` needs
|
||||||
back to the operating system: when `s` goes out of scope. When a variable
|
back to the operating system: when `s` goes out of scope. When a variable
|
||||||
binding goes out of scope, Rust calls a special function for us. This function
|
goes out of scope, Rust calls a special function for us. This function
|
||||||
is called `drop`, and it is where the author of `String` can put the code to
|
is called `drop`, and it is where the author of `String` can put the code to
|
||||||
return the memory. Rust calls `drop` automatically at the closing `}`.
|
return the memory. Rust calls `drop` automatically at the closing `}`.
|
||||||
|
|
||||||
> Note: This pattern is sometimes called *Resource Acquisition Is
|
Note: This pattern is sometimes called *Resource Acquisition Is
|
||||||
> Initialization* in C++, or RAII for short. While they are very similar,
|
Initialization* in C++, or RAII for short. While they are very similar,
|
||||||
> Rust’s take on this concept has a number of differences, so we don’t tend
|
Rust’s take on this concept has a number of differences, so we don’t tend
|
||||||
> to use the same term. If you’re familiar with this idea, keep in mind that it
|
to use the same term. If you’re familiar with this idea, keep in mind that it
|
||||||
> is *roughly* similar in Rust, but not identical.
|
is *roughly* similar in Rust, but not identical.
|
||||||
|
|
||||||
This pattern has a profound impact on the way that Rust code is written. It may
|
This pattern has a profound impact on the way that Rust code is written. It may
|
||||||
seem simple right now, but things can get tricky in more advanced situations
|
seem simple right now, but things can get tricky in more advanced situations
|
||||||
when we want to have multiple variable bindings use the data that we have
|
when we want to have multiple variables use the data that we have
|
||||||
allocated on the heap. Let’s go over some of those situations now.
|
allocated on the heap. Let’s go over some of those situations now.
|
||||||
|
|
||||||
#### Ways Bindings and Data Interact: Move
|
#### Ways Variables and Data Interact: Move
|
||||||
|
|
||||||
There are different ways that multiple bindings can interact with the same data
|
There are different ways that multiple variables can interact with the same data
|
||||||
in Rust. Let's take an example using an integer:
|
in Rust. Let’s take an example using an integer:
|
||||||
|
|
||||||
```rust
|
```rust
|
||||||
let x = 5;
|
let x = 5;
|
||||||
@@ -250,7 +250,7 @@ let y = x;
|
|||||||
|
|
||||||
We can probably guess what this is doing based on our experience with other
|
We can probably guess what this is doing based on our experience with other
|
||||||
languages: “Bind the value `5` to `x`, then make a copy of the value in `x` and
|
languages: “Bind the value `5` to `x`, then make a copy of the value in `x` and
|
||||||
bind it to `y`.” We now have two bindings, `x` and `y`, and both equal `5`.
|
bind it to `y`.” We now have two variables, `x` and `y`, and both equal `5`.
|
||||||
This is indeed what is happening since integers are simple values with a known,
|
This is indeed what is happening since integers are simple values with a known,
|
||||||
fixed size, and these two `5` values are pushed onto the stack.
|
fixed size, and these two `5` values are pushed onto the stack.
|
||||||
|
|
||||||
@@ -263,7 +263,7 @@ let s2 = s1;
|
|||||||
|
|
||||||
This looks very similar to the previous code, so we might assume that the way
|
This looks very similar to the previous code, so we might assume that the way
|
||||||
it works would be the same: that the second line would make a copy of the value
|
it works would be the same: that the second line would make a copy of the value
|
||||||
in `s1` and bind it to `s2`. This isn't quite what happens.
|
in `s1` and bind it to `s2`. This isn’t quite what happens.
|
||||||
|
|
||||||
To explain this more thoroughly, let’s take a look at what `String` looks like
|
To explain this more thoroughly, let’s take a look at what `String` looks like
|
||||||
under the covers in Figure 4-1. A `String` is made up of three parts, shown on
|
under the covers in Figure 4-1. A `String` is made up of three parts, shown on
|
||||||
@@ -273,24 +273,24 @@ is the memory that holds the contents, and this is on the heap.
|
|||||||
|
|
||||||
<img alt="String in memory" src="img/trpl04-01.svg" class="center" style="width: 50%;" />
|
<img alt="String in memory" src="img/trpl04-01.svg" class="center" style="width: 50%;" />
|
||||||
|
|
||||||
Figure 4-1: Representation in memory of a `String` holding the value "hello"
|
Figure 4-1: Representation in memory of a `String` holding the value `"hello"`
|
||||||
bound to `s1`
|
bound to `s1`
|
||||||
|
|
||||||
The length is how much memory, in bytes, the contents of the `String` is
|
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
|
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
|
`String` has gotten from the operating system. The difference between length
|
||||||
and capacity matters but not in this context, so for now, it's fine to ignore
|
and capacity matters but not in this context, so for now, it’s fine to ignore
|
||||||
the capacity.
|
the capacity.
|
||||||
|
|
||||||
When we assign `s1` to `s2`, the `String` data itself is copied, meaning we
|
When we assign `s1` to `s2`, the `String` data itself is copied, meaning we
|
||||||
copy the pointer, the length, and the capacity that are on the stack. We do not
|
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
|
copy the data on the heap that the `String`’s pointer refers to. In other
|
||||||
words, it looks like figure 4-2.
|
words, it looks like figure 4-2.
|
||||||
|
|
||||||
<img alt="s1 and s2 pointing to the same value" src="img/trpl04-02.svg" class="center" style="width: 50%;" />
|
<img alt="s1 and s2 pointing to the same value" src="img/trpl04-02.svg" class="center" style="width: 50%;" />
|
||||||
|
|
||||||
Figure 4-2: Representation in memory of the binding `s2` that has a copy of
|
Figure 4-2: Representation in memory of the variable `s2` that has a copy of
|
||||||
`s1`'s pointer, length and capacity
|
`s1`’s pointer, length and capacity
|
||||||
|
|
||||||
And *not* Figure 4-3, which is what memory would look like if Rust instead
|
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
|
copied the heap data as well. If Rust did this, the operation `s2 = s1` could
|
||||||
@@ -301,15 +301,15 @@ 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
|
Figure 4-3: Another possibility for what `s2 = s1` might do, if Rust chose to
|
||||||
copy heap data as well.
|
copy heap data as well.
|
||||||
|
|
||||||
Earlier, we said that when a binding goes out of scope, Rust will automatically
|
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 binding. But
|
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 location. This is
|
in figure 4-2, we see both data pointers pointing to the same location. This is
|
||||||
a problem: when `s2` and `s1` go out of scope, they will both try to free the
|
a problem: when `s2` and `s1` go out of scope, they will both try to free the
|
||||||
same memory. This is known as a *double free* error and is one of the memory
|
same memory. This is known as a *double free* error and is one of the memory
|
||||||
safety bugs we mentioned before. Freeing memory twice can lead to memory
|
safety bugs we mentioned before. Freeing memory twice can lead to memory
|
||||||
corruption, which can potentially lead to security vulnerabilities.
|
corruption, which can potentially lead to security vulnerabilities.
|
||||||
|
|
||||||
In order to ensure memory safety, there's one more detail to what happens in
|
In order to ensure memory safety, there’s one more detail to what happens in
|
||||||
this situation in Rust. Instead of trying to copy the allocated memory, Rust
|
this situation in Rust. Instead of trying to copy the allocated memory, Rust
|
||||||
says that `s1` is no longer valid and, therefore, doesn’t need to free anything
|
says that `s1` is no longer valid and, therefore, doesn’t need to free anything
|
||||||
when it goes out of scope. Check out what happens when you try to use `s1`
|
when it goes out of scope. Check out what happens when you try to use `s1`
|
||||||
@@ -334,11 +334,11 @@ println!("{}", s1);
|
|||||||
^~
|
^~
|
||||||
```
|
```
|
||||||
|
|
||||||
If you have heard the terms "shallow copy" and "deep copy" while working with
|
If you have heard the terms “shallow copy” and “deep copy” while working with
|
||||||
other languages, the concept of copying the pointer, length, and capacity
|
other languages, the concept of copying the pointer, length, and capacity
|
||||||
without copying the data probably sounds like a shallow copy. But because Rust
|
without copying the data probably sounds like a shallow copy. But because Rust
|
||||||
also invalidates the first binding, instead of calling this a shallow copy,
|
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*
|
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.
|
into `s2`. So what actually happens looks like Figure 4-4.
|
||||||
|
|
||||||
<img alt="s1 moved to s2" src="img/trpl04-04.svg" class="center" style="width: 50%;" />
|
<img alt="s1 moved to s2" src="img/trpl04-04.svg" class="center" style="width: 50%;" />
|
||||||
@@ -349,10 +349,10 @@ That solves our problem! With only `s2` valid, when it goes out of scope, it
|
|||||||
alone will free the memory, and we’re done.
|
alone will free the memory, and we’re done.
|
||||||
|
|
||||||
Furthermore, there’s a design choice that’s implied by this: Rust will never
|
Furthermore, there’s a design choice that’s implied by this: Rust will never
|
||||||
automatically create "deep" copies of your data. Therefore, any *automatic*
|
automatically create “deep” copies of your data. Therefore, any *automatic*
|
||||||
copying can be assumed to be inexpensive.
|
copying can be assumed to be inexpensive.
|
||||||
|
|
||||||
#### Ways Bindings and Data Interact: Clone
|
#### Ways Variables and Data Interact: Clone
|
||||||
|
|
||||||
If we *do* want to deeply copy the `String`’s data and not just the `String`
|
If we *do* want to deeply copy the `String`’s data and not just the `String`
|
||||||
itself, there’s a common method for that: `clone`. We will discuss methods in
|
itself, there’s a common method for that: `clone`. We will discuss methods in
|
||||||
@@ -388,19 +388,19 @@ let y = x;
|
|||||||
println!("x = {}, y = {}", x, y);
|
println!("x = {}, y = {}", x, y);
|
||||||
```
|
```
|
||||||
|
|
||||||
This seems to contradict what we just learned: we don't have a call to
|
This seems to contradict what we just learned: we don’t have a call to `clone`,
|
||||||
`clone`, but `x` is still valid, and wasn't moved into `y`.
|
but `x` is still valid, and wasn’t moved into `y`.
|
||||||
|
|
||||||
This is because types like integers that have a known size at compile time are
|
This is because types like integers that have a known size at compile time are
|
||||||
stored entirely on the stack, so copies of the actual values are quick to make.
|
stored entirely on the stack, so copies of the actual values are quick to make.
|
||||||
That means there's no reason we would want to prevent `x` from being valid
|
That means there’s no reason we would want to prevent `x` from being valid
|
||||||
after we create the binding `y`. In other words, there’s no difference between
|
after we create the variable `y`. In other words, there’s no difference between
|
||||||
deep and shallow copying here, so calling `clone` wouldn’t do anything
|
deep and shallow copying here, so calling `clone` wouldn’t do anything
|
||||||
differently from the usual shallow copying and we can leave it out.
|
differently from the usual shallow copying and we can leave it out.
|
||||||
|
|
||||||
Rust has a special annotation called the `Copy` trait that we can place on
|
Rust has a special annotation called the `Copy` trait that we can place on
|
||||||
types like these (we'll talk more about traits in Chapter XX). If a type has
|
types like these (we’ll talk more about traits in Chapter XX). If a type has
|
||||||
the `Copy` trait, an older binding is still usable after assignment. Rust will
|
the `Copy` trait, an older variable is still usable after assignment. Rust will
|
||||||
not let us annotate a type with the `Copy` trait if the type, or any of its
|
not let us annotate a type with the `Copy` trait if the type, or any of its
|
||||||
parts, has implemented `drop`. If the type needs something special to happen
|
parts, has implemented `drop`. If the type needs something special to happen
|
||||||
when the value goes out of scope and we add the `Copy` annotation to that type,
|
when the value goes out of scope and we add the `Copy` annotation to that type,
|
||||||
@@ -420,8 +420,8 @@ Here’s some of the types that are `Copy`:
|
|||||||
### Ownership and Functions
|
### Ownership and Functions
|
||||||
|
|
||||||
The semantics for passing a value to a function are similar to assigning a
|
The semantics for passing a value to a function are similar to assigning a
|
||||||
value to a binding. Passing a binding to a function will move or copy, just
|
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 bindings
|
like assignment. Here’s an example, with some annotations showing where variables
|
||||||
go into and out of scope:
|
go into and out of scope:
|
||||||
|
|
||||||
Filename: src/main.rs
|
Filename: src/main.rs
|
||||||
@@ -430,7 +430,7 @@ Filename: src/main.rs
|
|||||||
fn main() {
|
fn main() {
|
||||||
let s = String::from("hello"); // s comes into scope.
|
let s = String::from("hello"); // s comes into scope.
|
||||||
|
|
||||||
takes_ownership(s); // s's value moves into the function...
|
takes_ownership(s); // s’s value moves into the function...
|
||||||
// ... and so is no longer valid here.
|
// ... and so is no longer valid here.
|
||||||
let x = 5; // x comes into scope.
|
let x = 5; // x comes into scope.
|
||||||
|
|
||||||
@@ -438,7 +438,7 @@ fn main() {
|
|||||||
// but i32 is Copy, so it’s okay to still
|
// but i32 is Copy, so it’s okay to still
|
||||||
// use x afterward.
|
// use x afterward.
|
||||||
|
|
||||||
} // Here, x goes out of scope, then s. But since s's value was moved, nothing
|
} // Here, x goes out of scope, then s. But since s’s value was moved, nothing
|
||||||
// special happens.
|
// special happens.
|
||||||
|
|
||||||
fn takes_ownership(some_string: String) { // some_string comes into scope.
|
fn takes_ownership(some_string: String) { // some_string comes into scope.
|
||||||
@@ -458,7 +458,8 @@ and where the ownership rules prevent you from doing so.
|
|||||||
|
|
||||||
### Return Values and Scope
|
### Return Values and Scope
|
||||||
|
|
||||||
Returning values can also transfer ownership. Here's an example with similar annotations:
|
Returning values can also transfer ownership. Here’s an example with similar
|
||||||
|
annotations:
|
||||||
|
|
||||||
Filename: src/main.rs
|
Filename: src/main.rs
|
||||||
|
|
||||||
@@ -493,9 +494,9 @@ fn takes_and_gives_back(a_string: String) -> String { // a_string comes into sco
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
It’s the same pattern, every time: assigning a value to another binding moves
|
It’s the same pattern, every time: assigning a value to another variable moves
|
||||||
it, and when heap data values' bindings go out of scope, if the data hasn’t
|
it, and when heap data values’ variables go out of scope, if the data hasn’t
|
||||||
been moved to be owned by another binding, the value will be cleaned up by
|
been moved to be owned by another variable, the value will be cleaned up by
|
||||||
`drop`.
|
`drop`.
|
||||||
|
|
||||||
Taking ownership then returning ownership with every function is a bit tedious.
|
Taking ownership then returning ownership with every function is a bit tedious.
|
||||||
@@ -534,8 +535,9 @@ return the `String` back to the calling function so that we can still use the
|
|||||||
`String` after the call to `calculate_length`, since the `String` was moved
|
`String` after the call to `calculate_length`, since the `String` was moved
|
||||||
into `calculate_length`.
|
into `calculate_length`.
|
||||||
|
|
||||||
Here is how you would use a function without taking ownership of it using
|
Here is how you would define and use a `calculate_length` function that takes a
|
||||||
*references:*
|
*reference* to an object as an argument instead of taking ownership of the
|
||||||
|
argument:
|
||||||
|
|
||||||
Filename: src/main.rs
|
Filename: src/main.rs
|
||||||
|
|
||||||
@@ -549,13 +551,11 @@ fn main() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn calculate_length(s: &String) -> usize {
|
fn calculate_length(s: &String) -> usize {
|
||||||
let length = s.len();
|
s.len()
|
||||||
|
|
||||||
length
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
First, you’ll notice all of the tuple stuff in the binding declaration and the
|
First, you’ll notice all of the tuple stuff in the variable declaration and the
|
||||||
function return value is gone. Next, note that we pass `&s1` into
|
function return value is gone. Next, note that we pass `&s1` into
|
||||||
`calculate_length`, and in its definition, we take `&String` rather than
|
`calculate_length`, and in its definition, we take `&String` rather than
|
||||||
`String`.
|
`String`.
|
||||||
@@ -584,15 +584,13 @@ a reference as an argument. Let’s add some explanatory annotations:
|
|||||||
|
|
||||||
```rust
|
```rust
|
||||||
fn calculate_length(s: &String) -> usize { // s is a reference to a String
|
fn calculate_length(s: &String) -> usize { // s is a reference to a String
|
||||||
let length = s.len();
|
s.len()
|
||||||
|
|
||||||
length
|
|
||||||
} // Here, s goes out of scope. But since it does not have ownership of what
|
} // Here, s goes out of scope. But since it does not have ownership of what
|
||||||
// it refers to, nothing happens.
|
// it refers to, nothing happens.
|
||||||
```
|
```
|
||||||
|
|
||||||
It’s the same process as before, but we don’t drop what the reference points to
|
It’s the same process as before, but we don’t drop what the reference points to
|
||||||
when it goes out of scope because we don't have ownership. This lets us write
|
when it goes out of scope because we don’t have ownership. This lets us write
|
||||||
functions which take references as arguments instead of the values themselves,
|
functions which take references as arguments instead of the values themselves,
|
||||||
so that we won’t need to return them to give back ownership.
|
so that we won’t need to return them to give back ownership.
|
||||||
|
|
||||||
@@ -600,7 +598,7 @@ We call this process *borrowing*. Just like with real life, if a person owns
|
|||||||
something, you can borrow it from them, and when you’re done, you have to give
|
something, you can borrow it from them, and when you’re done, you have to give
|
||||||
it back.
|
it back.
|
||||||
|
|
||||||
So what happens if we try to modify something we're borrowing? Try this code
|
So what happens if we try to modify something we’re borrowing? Try this code
|
||||||
out. Spoiler alert: it doesn’t work!
|
out. Spoiler alert: it doesn’t work!
|
||||||
|
|
||||||
Filename: src/main.rs
|
Filename: src/main.rs
|
||||||
@@ -627,7 +625,7 @@ error: cannot borrow immutable borrowed content `*some_string` as mutable
|
|||||||
| ^^^^^^^^^^^
|
| ^^^^^^^^^^^
|
||||||
```
|
```
|
||||||
|
|
||||||
Just as bindings are immutable by default, so are references. We’re not allowed
|
Just as variables are immutable by default, so are references. We’re not allowed
|
||||||
to modify something we have a reference to.
|
to modify something we have a reference to.
|
||||||
|
|
||||||
### Mutable References
|
### Mutable References
|
||||||
@@ -685,10 +683,10 @@ mutate whenever you’d like. The benefit of having this restriction is that Rus
|
|||||||
can prevent data races at compile time. A *data race* is a particular type of
|
can prevent data races at compile time. A *data race* is a particular type of
|
||||||
race condition where two or more pointers access the same data at the same
|
race condition where two or more pointers access the same data at the same
|
||||||
time, at least one of the pointers is being used to write to the data, and
|
time, at least one of the pointers is being used to write to the data, and
|
||||||
there's no mechanism being used to synchronize access to the data. Data races
|
there’s no mechanism being used to synchronize access to the data. Data races
|
||||||
cause undefined behavior and can be difficult to diagnose and fix when trying
|
cause undefined behavior and can be difficult to diagnose and fix when trying
|
||||||
to track them down at runtime; Rust prevents this problem from happening since
|
to track them down at runtime; Rust prevents this problem from happening since
|
||||||
it won't even compile code with data races!
|
it won’t even compile code with data races!
|
||||||
|
|
||||||
As always, we can use `{}`s to create a new scope, allowing for multiple mutable
|
As always, we can use `{}`s to create a new scope, allowing for multiple mutable
|
||||||
references, just not *simultaneous* ones:
|
references, just not *simultaneous* ones:
|
||||||
@@ -733,17 +731,17 @@ error[E0502]: cannot borrow `s` as mutable because it is also borrowed as immuta
|
|||||||
Whew! We *also* cannot have a mutable reference while we have an immutable one.
|
Whew! We *also* cannot have a mutable reference while we have an immutable one.
|
||||||
Users of an immutable reference don’t expect the values to suddenly change out
|
Users of an immutable reference don’t expect the values to suddenly change out
|
||||||
from under them! Multiple immutable references are okay, however, since no one
|
from under them! Multiple immutable references are okay, however, since no one
|
||||||
who is just reading the data has the ability to affect anyone else's reading of
|
who is just reading the data has the ability to affect anyone else’s reading of
|
||||||
the data.
|
the data.
|
||||||
|
|
||||||
Even though these errors may be frustrating at times, remember that it's the
|
Even though these errors may be frustrating at times, remember that it’s the
|
||||||
Rust compiler pointing out a potential bug earlier (at compile time rather than
|
Rust compiler pointing out a potential bug earlier (at compile time rather than
|
||||||
at runtime) and showing you exactly where the problem is instead of you having
|
at runtime) and showing you exactly where the problem is instead of you having
|
||||||
to track down why sometimes your data isn't what you thought it should be.
|
to track down why sometimes your data isn’t what you thought it should be.
|
||||||
|
|
||||||
### Dangling References
|
### Dangling References
|
||||||
|
|
||||||
In languages with pointers, it's easy to make the error of creating a *dangling
|
In languages with pointers, it’s easy to make the error of creating a *dangling
|
||||||
pointer*, a pointer referencing a location in memory that may have been given
|
pointer*, a pointer referencing a location in memory that may have been given
|
||||||
to someone else, by freeing some memory while keeping around a pointer to that
|
to someone else, by freeing some memory while keeping around a pointer to that
|
||||||
memory. In Rust, by contrast, the compiler guarantees that references will
|
memory. In Rust, by contrast, the compiler guarantees that references will
|
||||||
@@ -784,12 +782,12 @@ error: aborting due to previous error
|
|||||||
```
|
```
|
||||||
|
|
||||||
This error message refers to a feature we haven’t learned about yet:
|
This error message refers to a feature we haven’t learned about yet:
|
||||||
*lifetimes*. We'll discuss lifetimes in detail in Chapter XX, but, disregarding
|
*lifetimes*. We’ll discuss lifetimes in detail in Chapter XX, but, disregarding
|
||||||
the parts about lifetimes, the message does contain the key to why this code is
|
the parts about lifetimes, the message does contain the key to why this code is
|
||||||
a problem: `this function’s return type contains a borrowed value, but there is
|
a problem: `this function’s return type contains a borrowed value, but there is
|
||||||
no value for it to be borrowed from`.
|
no value for it to be borrowed from`.
|
||||||
|
|
||||||
Let’s have a closer look at exactly what's happenening at each stage of our
|
Let’s have a closer look at exactly what’s happening at each stage of our
|
||||||
`dangle` code:
|
`dangle` code:
|
||||||
|
|
||||||
```rust,ignore
|
```rust,ignore
|
||||||
@@ -828,7 +826,7 @@ Here’s a recap of what we’ve talked about:
|
|||||||
2. Any number of immutable references.
|
2. Any number of immutable references.
|
||||||
2. References must always be valid.
|
2. References must always be valid.
|
||||||
|
|
||||||
Next, let's look at a different kind of reference: slices.
|
Next, let’s look at a different kind of reference: slices.
|
||||||
|
|
||||||
## Slices
|
## Slices
|
||||||
|
|
||||||
@@ -922,13 +920,13 @@ fn main() {
|
|||||||
|
|
||||||
s.clear(); // This empties the String, making it equal to "".
|
s.clear(); // This empties the String, making it equal to "".
|
||||||
|
|
||||||
// word still has the value 5 here, but there's no more string that
|
// word still has the value 5 here, but there’s no more string that
|
||||||
// we could meaningfully use the value 5 with. word is now totally invalid!
|
// we could meaningfully use the value 5 with. word is now totally invalid!
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
This program compiles without any errors, and also would if we used `word`
|
This program compiles without any errors, and also would if we used `word`
|
||||||
after calling `s.clear()`. `word` isn't connected to the state of `s` at all,
|
after calling `s.clear()`. `word` isn’t connected to the state of `s` at all,
|
||||||
so `word` still contains the value `5`. We could use that `5` with `s` to try
|
so `word` still contains the value `5`. We could use that `5` with `s` to try
|
||||||
to extract the first word out, but this would be a bug since the contents of
|
to extract the first word out, but this would be a bug since the contents of
|
||||||
`s` have changed since we saved `5` in `word`.
|
`s` have changed since we saved `5` in `word`.
|
||||||
@@ -941,8 +939,8 @@ fn second_word(s: &String) -> (usize, usize) {
|
|||||||
```
|
```
|
||||||
|
|
||||||
Now we’re tracking both a start *and* an ending index, and we have even more
|
Now we’re tracking both a start *and* an ending index, and we have even more
|
||||||
values that were calculated from data in a particular state but aren't tied to
|
values that were calculated from data in a particular state but aren’t tied to
|
||||||
that state at all. We now have three unrelated variable bindings floating
|
that state at all. We now have three unrelated variables floating
|
||||||
around which need to be kept in sync.
|
around which need to be kept in sync.
|
||||||
|
|
||||||
Luckily, Rust has a solution to this problem: string slices.
|
Luckily, Rust has a solution to this problem: string slices.
|
||||||
@@ -972,7 +970,7 @@ Figure 4-6 shows this in a diagram:
|
|||||||
|
|
||||||
<img alt="world containing a pointer to the 6th byte of String s and a length 5" src="img/trpl04-06.svg" class="center" style="width: 50%;" />
|
<img alt="world containing a pointer to the 6th byte of String s and a length 5" src="img/trpl04-06.svg" class="center" style="width: 50%;" />
|
||||||
|
|
||||||
Figure 4-6: Two string slices referring to parts 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),
|
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:
|
you can drop the value before the `..`. In other words, these are equal:
|
||||||
@@ -1010,7 +1008,7 @@ let slice = &s[..];
|
|||||||
```
|
```
|
||||||
|
|
||||||
With this in mind, let’s re-write `first_word` to return a slice. The type
|
With this in mind, let’s re-write `first_word` to return a slice. The type
|
||||||
that signifies "string slice" is written as `&str`:
|
that signifies “string slice” is written as `&str`:
|
||||||
|
|
||||||
Filename: src/main.rs
|
Filename: src/main.rs
|
||||||
|
|
||||||
@@ -1045,7 +1043,7 @@ fn second_word(s: &String) -> &str {
|
|||||||
|
|
||||||
We now have a straightforward API that’s much harder to mess up. Remember our
|
We now have a straightforward API that’s much harder to mess up. Remember our
|
||||||
bug from before, when we got the first word but then cleared the string so that
|
bug from before, when we got the first word but then cleared the string so that
|
||||||
our first word was invalid? That code was logically incorrect but didn't show
|
our first word was invalid? That code was logically incorrect but didn’t show
|
||||||
any immediate errors. The problems would show up later, if we kept trying to
|
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
|
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
|
impossible, and let us know we have a problem with our code much sooner. Using
|
||||||
@@ -1170,9 +1168,9 @@ The concepts of ownership, borrowing, and slices are what ensure memory safety
|
|||||||
in Rust programs at compile time. Rust is a language that gives you control
|
in Rust programs at compile time. Rust is a language that gives you control
|
||||||
over your memory usage like other systems programming languages, but having the
|
over your memory usage like other systems programming languages, but having the
|
||||||
owner of data automatically clean up that data when the owner goes out of scope
|
owner of data automatically clean up that data when the owner goes out of scope
|
||||||
means you don't have to write and debug extra code to get this control.
|
means you don’t have to write and debug extra code to get this control.
|
||||||
|
|
||||||
Ownership affects how lots of other parts of Rust work, so we will be talking
|
Ownership affects how lots of other parts of Rust work, so we will be talking
|
||||||
about these concepts further throughout the rest of the book. Let's move on to
|
about these concepts further throughout the rest of the book. Let’s move on to
|
||||||
the next chapter where we'll look at grouping pieces of data together in a
|
the next chapter where we’ll look at grouping pieces of data together in a
|
||||||
`struct`.
|
`struct`.
|
||||||
|
|||||||
Reference in New Issue
Block a user