mirror of
https://github.com/rust-lang/book.git
synced 2026-11-30 20:04:31 -06:00
@@ -1,16 +1,16 @@
|
||||
# Common Programming Concepts in Rust
|
||||
|
||||
Let's look at concepts that appear in almost every programming language 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 Rust, but
|
||||
we’ll discuss Rust’s particular syntax and conventions concerning these common
|
||||
concepts.
|
||||
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
|
||||
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
|
||||
these common concepts.
|
||||
|
||||
Specifically, we’ll be talking about variable bindings, basic types, functions,
|
||||
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.
|
||||
|
||||
PROD: START BOX
|
||||
<!-- PROD: START BOX -->
|
||||
|
||||
Keep in mind as we get into variables and functions that the Rust language has
|
||||
a set of *keywords* that have been reserved for use by the language only, much
|
||||
@@ -21,4 +21,4 @@ current functionality associated but have been reserved for functionality that
|
||||
might be in the Rust language in the future. You can find a list of the
|
||||
keywords in Appendix XX.
|
||||
|
||||
PROD: END BOX
|
||||
<!-- PROD: END BOX -->
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
## Variable Bindings and Mutability
|
||||
|
||||
We mentioned in Chapter XX that by default, variable bindings are *immutable*.
|
||||
This is one of many nudges that Rust's design has to encourage us to write our
|
||||
code to get 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 explore
|
||||
how and why Rust encourages us to favor immutability, and why we might want to
|
||||
opt out of that.
|
||||
We mentioned in Chapter 2 that by default, variable bindings are *immutable*.
|
||||
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
|
||||
offer. We still have the option to make our bindings mutable, though. Let's
|
||||
explore how and why Rust encourages us to favor immutability, and why we might
|
||||
want to opt out of that.
|
||||
|
||||
Variable bindings being immutable means that once a value is bound, you can't
|
||||
change that value. To illustrate this, let's generate a new project in your
|
||||
@@ -41,17 +41,16 @@ note: prior assignment occurs here
|
||||
|> ^
|
||||
```
|
||||
|
||||
This is an 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
|
||||
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
|
||||
errors. Try to keep in mind that 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
|
||||
######Extended Error Explanations
|
||||
<!-- PROD: START BOX -->
|
||||
###### Extended Error Explanations
|
||||
|
||||
Now that you've seen a few examples of Rust errors, let's look at one
|
||||
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
|
||||
information on the kind of error you've received with output like this:
|
||||
|
||||
@@ -62,8 +61,8 @@ error: re-assignment of immutable variable `x` [--explain E0384]
|
||||
This tells us that if we pass the `--explain` flag to `rustc` with the provided
|
||||
error code, we can see an extended explanation which will try to explain common
|
||||
causes of and solutions to that kind of error. Not every error has a longer
|
||||
explanation, but many do. Here’s the explanation for the `E0384` error we
|
||||
received:
|
||||
explanation, but many do. Here’s a portion of the explanation for the `E0384`
|
||||
error we received:
|
||||
|
||||
````bash
|
||||
$ rustc --explain E0384
|
||||
@@ -76,45 +75,36 @@ fn main(){
|
||||
x = 5; // error, reassignment of immutable variable
|
||||
}
|
||||
```
|
||||
|
||||
By default, variables in Rust are immutable. To fix this error, add the keyword
|
||||
`mut` after the keyword `let` when declaring the variable. For example:
|
||||
|
||||
```
|
||||
fn main(){
|
||||
let mut x = 3;
|
||||
x = 5;
|
||||
}
|
||||
```
|
||||
````
|
||||
|
||||
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
|
||||
to help.
|
||||
|
||||
PROD: END BOX
|
||||
<!-- PROD: END BOX -->
|
||||
|
||||
The error includes the message `re-assigment of immutable variable` because the
|
||||
program tried to assign a second value to the `x` variable.
|
||||
The error tells us that the cause of the error is `re-assigment of immutable
|
||||
variable`, because we tried to assign a second value to the immutable `x`
|
||||
variable.
|
||||
|
||||
Getting compile-time errors when your code attempts to change a value that it
|
||||
previously said was immutable is important because this very situation can lead
|
||||
to bugs. If one part of your code operates on an assumption that a value it's
|
||||
operating on will never change, and another part of your code changes that
|
||||
value, it's possible that the first code won't do what it was designed to do.
|
||||
Especially when the second piece of code only changes the value _sometimes_,
|
||||
this cause of bugs can be difficult to track down after the fact.
|
||||
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
|
||||
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
|
||||
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
|
||||
when the second piece of code only changes the value _sometimes_.
|
||||
|
||||
In Rust, our code can know that a value our code assumes won't change really
|
||||
won't change, 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 might change. This can make code easier to reason about.
|
||||
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
|
||||
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.
|
||||
|
||||
Mutability is really useful, though! Bindings are immutable only by default;
|
||||
you can make them mutable by adding `mut` in front of the variable name. In
|
||||
addition to telling the compiler it should allow this value to be changed, it
|
||||
conveys intent to future readers of the code and says that other parts of the
|
||||
code will be changing this value.
|
||||
Mutability can be really useful, though! Bindings are immutable only by
|
||||
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
|
||||
future readers of the code by indicating that other parts of the code will be
|
||||
changing this value.
|
||||
|
||||
For example, change the program you just wrote to the following:
|
||||
|
||||
@@ -140,21 +130,20 @@ The value of x is: 6
|
||||
```
|
||||
|
||||
Using `mut`, we are allowed to change the value that `x` binds to from `5` to
|
||||
`6`. You might want to make a binding mutable because it makes the code easier
|
||||
to understand than an implementation that only uses immutable bindings. In
|
||||
cases where you're using large data structures, mutating an 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.
|
||||
`6`. In some cases you'll want to make a binding mutable because it makes the
|
||||
code easier to understand than an implementation that only uses immutable
|
||||
bindings. In cases where you're using large data structures, mutating an
|
||||
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.
|
||||
|
||||
### Shadowing
|
||||
|
||||
As we saw in the guessing game tutorial, we can declare new bindings with the
|
||||
same name as a previous binding, and the new binding *shadows* the previous
|
||||
binding. When we say the first binding is *shadowed* by the second, it means
|
||||
the second binding's value is what you will see when you use the variable
|
||||
after the second binding. This can be useful if you’d like to perform a few
|
||||
transformations on a value, but have the binding be immutable after those
|
||||
transformations have been completed. For example:
|
||||
binding. We say that the first binding is *shadowed* by the second, which means
|
||||
that the second binding'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
|
||||
of the `let` keyword as follows:
|
||||
|
||||
Filename: src/main.rs
|
||||
|
||||
@@ -170,9 +159,9 @@ fn main() {
|
||||
}
|
||||
```
|
||||
|
||||
This program first binds `x` to a value of `5`. Then, it shadows `x` by saying
|
||||
`let x =` again, taking the original value and adding `1` so that the value of
|
||||
`x` is then `6`. The third `let` statement also shadows `x`, taking the
|
||||
This program first binds `x` to a value of `5`. Then, it shadows `x` by
|
||||
repeating `let x =`, taking the original value and adding `1` so that the value
|
||||
of `x` is then `6`. The third `let` statement also shadows `x`, taking the
|
||||
previous value and multiplying it by `2` to give `x` a final value of `12`. If
|
||||
you run this, it will output:
|
||||
|
||||
@@ -183,8 +172,48 @@ $ cargo run
|
||||
The value of x is: 12
|
||||
```
|
||||
|
||||
Shadowing is useful because it lets us modify `x` without having to make the
|
||||
binding mutable. This means the compiler will still keep us from accidentally
|
||||
trying to mutate `x` directly later.
|
||||
This is different from marking a binding as `mut` because unless we use the
|
||||
`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
|
||||
have the binding be immutable after those transformations have been completed.
|
||||
|
||||
Now let's look at some of the types of values that we can bind variables to.
|
||||
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
|
||||
change the type of the value we're binding to but reuse the same name. For
|
||||
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
|
||||
number:
|
||||
|
||||
```rust
|
||||
let spaces = " ";
|
||||
let spaces = spaces.len();
|
||||
```
|
||||
|
||||
This is allowed: the first `spaces` binding is a string type, and the second
|
||||
`spaces` binding, which is a brand new binding that happens to have the same
|
||||
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
|
||||
the simpler `spaces` name. If we try to use `mut` for this, however, like this:
|
||||
|
||||
```rust,ignore
|
||||
let mut spaces = " ";
|
||||
spaces = spaces.len();
|
||||
```
|
||||
|
||||
We will get a compile-time error because we are not allowed to mutate a
|
||||
binding's type:
|
||||
|
||||
```bash
|
||||
error: mismatched types [--explain E0308]
|
||||
-->
|
||||
|>
|
||||
4 |> spaces = spaces.len();
|
||||
|> ^^^^^^^^^^^^ expected &-ptr, found usize
|
||||
note: expected type `&str`
|
||||
note: found type `usize`
|
||||
|
||||
error: aborting due to previous error
|
||||
```
|
||||
|
||||
Now that we've explored how variable bindings work, let's look at some more
|
||||
data types of values that we can bind variables to.
|
||||
|
||||
+85
-60
@@ -2,28 +2,41 @@
|
||||
|
||||
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
|
||||
look at a number of types built into the language itself split into two subsets
|
||||
of Rust data types: scalar and compound.
|
||||
look at a number of types built into the language itself split into two subsets:
|
||||
scalar and compound.
|
||||
|
||||
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
|
||||
time. The compiler can usually infer what type we want to use based on the
|
||||
value and how we use it. When many types are possible, such as when we
|
||||
converted a `String` to a numeric type using `parse` in the guessing game
|
||||
tutorial, we can add a type annotation, like this:
|
||||
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
|
||||
add a type annotation, like this:
|
||||
|
||||
```rust,ignore
|
||||
let x: i32 = 5;
|
||||
```rust
|
||||
let guess: u32 = "42".parse().unwrap();
|
||||
```
|
||||
|
||||
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
|
||||
we want:
|
||||
|
||||
```bash
|
||||
error: unable to infer enough type information about `_`; type annotations or
|
||||
generic parameter binding required [--explain E0282]
|
||||
-->
|
||||
|>
|
||||
3 |> let guess = "42".parse().unwrap();
|
||||
|> ^^^^^
|
||||
```
|
||||
|
||||
You will see some type annotations as we discuss the various data types.
|
||||
|
||||
### Scalar Types
|
||||
|
||||
A *scalar* type is one that represents a single value. There are four key
|
||||
scalar types in Rust: integers, floating point numbers, booleans, and
|
||||
characters. You'll likely recognize these from other programming languages, but
|
||||
let's jump into how they work in Rust.
|
||||
A *scalar* type represents a single value. There are four primary scalar
|
||||
types in Rust: integers, floating point numbers, booleans, and characters.
|
||||
You'll likely recognize these from other programming languages, but let's jump
|
||||
into how they work in Rust.
|
||||
|
||||
#### Integer Types
|
||||
|
||||
@@ -41,19 +54,26 @@ built-in integer types in Rust, shown in Table 3-1.
|
||||
| 64-bit | i64 | u64 |
|
||||
| arch | isize | usize |
|
||||
|
||||
*Table 4-1: Integer types in Rust. Each code (for example, i32) can be used to
|
||||
declare the type of a value.*
|
||||
*Table 3-1: Integer types in Rust. Each variant in the signed and unsigned
|
||||
columns (for example, `i32`) can be used to declare the type of an integer
|
||||
value.*
|
||||
|
||||
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
|
||||
either negative or positive, meaning the number needs to have a 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 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.
|
||||
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 outside the
|
||||
scope of this text).
|
||||
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
|
||||
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
|
||||
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
|
||||
you're unsure what this is you can search for it online; an explanation is
|
||||
outside the scope of this text).
|
||||
|
||||
Each signed variant can store numbers from -(2<sup>n - 1</sup>) to 2<sup>n -
|
||||
1</sup> - 1 inclusive, where `n` is the number of bits that variant uses. So an
|
||||
`i8` can store from -(2<sup>7</sup>) to 2<sup>7</sup>, which equals -128
|
||||
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.
|
||||
|
||||
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
|
||||
@@ -76,8 +96,7 @@ all number literals except for the byte literal allow a type suffix, such as
|
||||
So how do you know which type of integer to use? If you're unsure, Rust's
|
||||
defaults are generally good choices, and integer types default to `i32`: it’s
|
||||
generally the fastest, even on 64-bit systems. The primary situation in which
|
||||
you'd need to specify `isize` or `usize` is when indexing some sort of
|
||||
collection, which we'll talk about in the "Arrays" section.
|
||||
you'd use `isize` or `usize` is when indexing some sort of collection.
|
||||
|
||||
#### Floating-Point Types
|
||||
|
||||
@@ -88,7 +107,8 @@ 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
|
||||
`f32` on those systems. Most of the time, trading potential worse performance
|
||||
for better precision is a reasonable initial choice, and you should benchmark
|
||||
your code if you suspect floating-point size is a problem in your case.
|
||||
your code if you suspect floating-point size is a problem in your case. See
|
||||
Chapter XX for how to run benchmarks.
|
||||
|
||||
Here's an example showing floating-point numbers in action:
|
||||
|
||||
@@ -177,10 +197,7 @@ 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`
|
||||
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`
|
||||
is in Rust. It also means that `char`s are four bytes each. You can learn more
|
||||
about Unicode Scalar Values at
|
||||
*http://www.unicode.org/glossary/#unicode_scalar_value* and find a chart for
|
||||
all unicode code points at *http://www.unicode.org/charts/*.
|
||||
is in Rust. We'll discuss this in detail in the Strings section of Chapter 8.
|
||||
|
||||
### Compound Types
|
||||
|
||||
@@ -189,12 +206,13 @@ has two primitive compound types: tuples and arrays.
|
||||
|
||||
#### Grouping Values into Tuples
|
||||
|
||||
We’ve seen tuples already, when binding multiple values at once. A tuple is a
|
||||
general way of grouping together some number of other values with distinct
|
||||
types into one compound type.
|
||||
A tuple is a general way of grouping together some number of other values with
|
||||
distinct types into one compound type.
|
||||
|
||||
We create a tuple by writing a comma-separated list of values inside
|
||||
parentheses. Each position in the tuple has a distinct type, as in this example:
|
||||
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
|
||||
optional type annotations in this example:
|
||||
|
||||
Filename: src/main.rs
|
||||
|
||||
@@ -204,16 +222,16 @@ fn main() {
|
||||
}
|
||||
```
|
||||
|
||||
Note that, unlike the examples of multiple bindings, here we bind the single
|
||||
name `tup` to the entire tuple, emphasizing the fact that a tuple is considered
|
||||
a single compound element. We could then use pattern matching to destructure
|
||||
this tuple value, like this:
|
||||
Note that the single name `tup` binds to the entire tuple, emphasizing the fact
|
||||
that a tuple is considered a single compound element. To get the individual
|
||||
values out of a tuple, we can use pattern matching to destructure a tuple
|
||||
value, like this:
|
||||
|
||||
Filename: src/main.rs
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let tup: (i32, f64, u8) = (500, 6.4, 1);
|
||||
let tup = (500, 6.4, 1);
|
||||
|
||||
let (x, y, z) = tup;
|
||||
|
||||
@@ -224,9 +242,8 @@ fn main() {
|
||||
In this program, we first create a tuple and bind it to the name `tup`. We 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
|
||||
the single tuple into three parts.
|
||||
|
||||
Finally, we print the value of `y`, which is `6.4`.
|
||||
the single tuple into three parts. Finally, we print the value of `y`, which is
|
||||
`6.4`.
|
||||
|
||||
#### Tuple Indexing
|
||||
|
||||
@@ -257,8 +274,7 @@ tuple is 0.
|
||||
Another way to bind a name to a collection of multiple values is with an
|
||||
*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
|
||||
in Rust have a fixed length at compile time -- they cannot grow or shrink in
|
||||
size.
|
||||
in Rust have a fixed length: once declared, they cannot grow or shrink in size.
|
||||
|
||||
In Rust, the values going into an array are written as a comma separated list
|
||||
inside square brackets:
|
||||
@@ -271,11 +287,21 @@ fn main() {
|
||||
}
|
||||
```
|
||||
|
||||
While arrays can be useful since they are a primitive type, they aren't as
|
||||
flexible as the `Vec` (short for "vector"), a 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 `Vec`, you should probably go with a `Vec`,
|
||||
and we'll discuss them in more detail in chapter XX.
|
||||
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
|
||||
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,
|
||||
you should probably go with a vector, and we'll discuss them in more detail in
|
||||
Chapter 8.
|
||||
|
||||
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
|
||||
we can use an array since we know we will always have 12 items:
|
||||
|
||||
```rust
|
||||
let months = ["January", "February", "March", "April", "May", "June", "July",
|
||||
"August", "September", "October", "November", "December"];
|
||||
```
|
||||
|
||||
#### Accessing Array Elements
|
||||
|
||||
@@ -293,14 +319,11 @@ fn main() {
|
||||
}
|
||||
```
|
||||
|
||||
In this example, the `first` variable will bind to `1` at index `[0]` in the
|
||||
array, and `second` will bind to `2` at index `[1]` in the array. Note that
|
||||
these values are copied out of the array and into `first` and `second` when the
|
||||
`let` statement is called. That means if the array changes after the `let`
|
||||
statements, these bindings will not, and the two variables should retain their
|
||||
values.
|
||||
In this example, the binding named `first` will get the value `1`, since that
|
||||
is the value at index `[0]` in the array. The binding named `second` will get
|
||||
the value `2` from index `[1]` in the array.
|
||||
|
||||
#### Invalid array element access
|
||||
#### Invalid Array Element Access
|
||||
|
||||
What happens if you try to access an element of an array past the end of the
|
||||
array? Say we changed our program to:
|
||||
@@ -323,16 +346,18 @@ Running this code with `cargo run` produces:
|
||||
$ cargo run
|
||||
Compiling arrays v0.1.0 (file:///projects/arrays)
|
||||
Running `target/debug/arrays`
|
||||
thread '<main>' panicked at 'index out of bounds: the len is 5 but the index is 10', src/main.rs:4
|
||||
thread '<main>' panicked at 'index out of bounds: the len is 5 but the index is
|
||||
10', src/main.rs:4
|
||||
note: Run with `RUST_BACKTRACE=1` for a backtrace.
|
||||
error: Process didn't exit successfully: `target/debug/arrays` (exit code: 101)
|
||||
```
|
||||
|
||||
We can see that compiling did not give us any errors, but we got a *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 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 with an error.
|
||||
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
|
||||
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
|
||||
length, it will "panic", which is what it's called when a Rust program exits
|
||||
with an error.
|
||||
|
||||
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
|
||||
|
||||
@@ -76,10 +76,10 @@ $ cargo run
|
||||
The value of x is: 5
|
||||
```
|
||||
|
||||
Since we passed `5` to `another_function`, the `println!` macro put `5` where
|
||||
the pair of curly braces were in the format string. The declaration of
|
||||
`another_function` shows that it takes one argument named `x`, and the type
|
||||
of `x` is `i32`.
|
||||
In the declaration of `another_function`, we place one argument named `x`. We
|
||||
specify the type of `x` as `i32`. When we pass `5` to `another_function`,
|
||||
the `println!` macro puts `5` where the pair of curly braces were in the format
|
||||
string.
|
||||
|
||||
In function signatures, we _must_ declare the type. This is a deliberate
|
||||
decision in the design of Rust; requiring type annotations in function
|
||||
@@ -123,7 +123,7 @@ the two strings are printed with these values.
|
||||
|
||||
### Function Bodies
|
||||
|
||||
Function bodies are made up of a series of statements ending in an optional
|
||||
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
|
||||
we have seen expressions as parts of statements. Since Rust is an
|
||||
expression-based language, this is an important distinction to understand.
|
||||
@@ -137,8 +137,8 @@ We've already been using both statements and expressions. *Statements* are
|
||||
instructions that perform some action and do not return a value. *Expressions*
|
||||
evaluate to a resulting value. Let's look at some examples.
|
||||
|
||||
`Let` bindings are statements. They instruct the program to create a binding
|
||||
name and assign a value to it. `let y = 6;` in this example is a statement:
|
||||
Creating a variable binding and assigning a value to it with the `let` keyword
|
||||
is a statement. In this example, `let y = 6;` is a statement:
|
||||
|
||||
Filename: src/main.rs
|
||||
|
||||
@@ -148,8 +148,8 @@ fn main() {
|
||||
}
|
||||
```
|
||||
|
||||
Function definitions are also statements-- so the entire previous example is a
|
||||
statement as well.
|
||||
Function definitions are also statements; the entire previous example is a
|
||||
statement in itself.
|
||||
|
||||
Statements do not return values themselves. Therefore, you can’t assign a `let`
|
||||
binding to another binding, as this code tries to do:
|
||||
@@ -179,12 +179,13 @@ error: Could not compile `functions`.
|
||||
|
||||
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
|
||||
the assignment returns the value of the assignment. In those languages, you
|
||||
could write `x = y = 6` and have both `x` and `y` have the value `6`, but that
|
||||
is not the case in Rust.
|
||||
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
|
||||
case in Rust.
|
||||
|
||||
Expressions are most of the rest of the code that you will write in Rust.
|
||||
Consider a simple math operation, like this:
|
||||
Expressions are code that evaluate to something, and make up most of the rest
|
||||
of the code that you will write in Rust. Consider a simple math operation, like
|
||||
this:
|
||||
|
||||
```rust,ignore
|
||||
5 + 6
|
||||
@@ -210,6 +211,9 @@ fn main() {
|
||||
println!("The value of y is: {}", y);
|
||||
}
|
||||
```
|
||||
<!-- 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.
|
||||
I'm flagging this as a reminder for when we transfer to libreoffice -->
|
||||
|
||||
The expression:
|
||||
|
||||
@@ -220,11 +224,11 @@ The expression:
|
||||
}
|
||||
```
|
||||
|
||||
is a block that, in this case, gets evaluated to `4`, which then gets bound to
|
||||
is a block that, in this case, evaluates to `4`, and then gets bound to
|
||||
`y` as part of the `let` statement.
|
||||
|
||||
Note that the line containing `x + 1` does not have a semicolon at the end like
|
||||
most of the lines we've seen up until now have had. This is the most important
|
||||
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
|
||||
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
|
||||
expression, that will turn it into a statement, which will then not return a
|
||||
@@ -234,7 +238,7 @@ 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
|
||||
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
|
||||
function that returns a value:
|
||||
|
||||
@@ -254,8 +258,8 @@ fn main() {
|
||||
|
||||
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
|
||||
Rust. Note the function's return type, too. Try running this code, and the
|
||||
output should look like this:
|
||||
Rust. Note the function's return type is specified, too, as `-> i32`. Try
|
||||
running this code, and the output should look like this:
|
||||
|
||||
```bash
|
||||
$ cargo run
|
||||
@@ -264,10 +268,10 @@ $ cargo run
|
||||
The value of x is: 5
|
||||
```
|
||||
|
||||
The `5` in the `five` function is actually 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. First, the line `let x = five();` in `main` shows that we
|
||||
can use the return value of a function to initialize a binding.
|
||||
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.
|
||||
First, the line `let x = five();` shows us using the return value of a function
|
||||
to initialize a binding.
|
||||
|
||||
Because the function `five` returns a `5`, that line is the same as saying:
|
||||
|
||||
|
||||
+85
-55
@@ -1,15 +1,15 @@
|
||||
## Control Flow
|
||||
|
||||
Deciding whether or not to run some code depending on if a condition is true,
|
||||
or deciding to run some code repeatedly while a condition is true, are basic
|
||||
building blocks in most programming languages. The most common constructs that
|
||||
let us control the flow of execution of our Rust code are `if` expressions and
|
||||
loops.
|
||||
Decisions on whether or not to run some code depending on if a condition is
|
||||
true, or deciding to run some code repeatedly while a condition is true, are
|
||||
basic building blocks in most programming languages. The most common constructs
|
||||
that let us control the flow of execution of our Rust code are `if` expressions
|
||||
and loops.
|
||||
|
||||
### `if` Expressions
|
||||
|
||||
An `if` expression allows us to branch our code depending on conditions. We
|
||||
provide a condition and then say, "If this condition is met, then 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."
|
||||
|
||||
Let’s make a new project to explore `if`, called `branches`. In `src/main.rs`,
|
||||
@@ -29,13 +29,15 @@ fn main() {
|
||||
}
|
||||
```
|
||||
|
||||
All `if` expressions start with `if`, which is followed by a condition. In this
|
||||
case, our condition is checking if our variable binding `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 braces. These blocks
|
||||
are sometimes called *arms*. We can optionally also include an `else`
|
||||
statement, which we have chosen to do here. `else` gives the program a block of
|
||||
code to execute should `condition` evaluate to false.
|
||||
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
|
||||
`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
|
||||
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
|
||||
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,
|
||||
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:
|
||||
|
||||
@@ -62,7 +64,7 @@ $ cargo run
|
||||
condition was false
|
||||
```
|
||||
|
||||
It’s also worth noting that `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:
|
||||
|
||||
Filename: src/main.rs
|
||||
@@ -96,7 +98,9 @@ Could not compile `branches`.
|
||||
The error tells us that Rust expected a `bool`, but got an integer. Rust will
|
||||
not automatically try to convert non-boolean types to a boolean here, unlike
|
||||
languages like Ruby or JavaScript. We must be explicit and always give `if` a
|
||||
`boolean` as its condition. If your intention is for the `if` code block to be run if a number is not equal to `0`, for example, we would change the `if` expression to read:
|
||||
`boolean` as its condition. If you wanted your `if` code block to run only when
|
||||
a number is not equal to `0`, for example, we would change the `if` expression
|
||||
to read:
|
||||
|
||||
Filename: src/main.rs
|
||||
|
||||
@@ -110,7 +114,7 @@ fn main() {
|
||||
}
|
||||
```
|
||||
|
||||
Running this will print "number was something other than zero".
|
||||
Running this will print `number was something other than zero`.
|
||||
|
||||
#### Multiple Conditions with `else if`
|
||||
|
||||
@@ -121,16 +125,16 @@ Filename: src/main.rs
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let number = 5;
|
||||
let number = 6;
|
||||
|
||||
if number == 3 {
|
||||
println!("number was 3");
|
||||
} else if number == 4 {
|
||||
println!("number was 4");
|
||||
} else if number == 5 {
|
||||
println!("number was 5");
|
||||
if number % 4 == 0 {
|
||||
println!("number is divisible by 4");
|
||||
} else if number % 3 == 0 {
|
||||
println!("number is divisible by 3");
|
||||
} else if number % 2 == 0 {
|
||||
println!("number is divisible by 2");
|
||||
} else {
|
||||
println!("number was something else");
|
||||
println!("number is not divisible by 4, 3, or 2");
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -142,11 +146,15 @@ should see output like this:
|
||||
$ cargo run
|
||||
Compiling branches v0.1.0 (file:///projects/branches)
|
||||
Running `target/debug/branches`
|
||||
condition was 5
|
||||
number is divisible by 3
|
||||
```
|
||||
|
||||
When this program executes, it will check each `if` expression in turn and
|
||||
execute the first body for which the condition holds true.
|
||||
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
|
||||
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
|
||||
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
|
||||
yourself with more than one, you may want to look at refactoring your code. In
|
||||
@@ -155,7 +163,7 @@ for these cases.
|
||||
|
||||
#### Using `if` in a Binding
|
||||
|
||||
The last detail you need to learn 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
|
||||
instance:
|
||||
|
||||
@@ -186,8 +194,8 @@ The value of number is: 5
|
||||
|
||||
Remember, blocks of code evaluate to the last expression in them, and numbers
|
||||
by themselves are also expressions. In this case, the value of the whole `if`
|
||||
expression depends on which block of code executes. This means that the value
|
||||
that results from both arms of the `if` must be the same type; in the previous
|
||||
expression depends on which block of code executes. This means the value that
|
||||
results from both arms of the `if` must be the same type; in the previous
|
||||
example, they were both `i32` integers. But what happens if the types are
|
||||
mismatched, as in the following example?
|
||||
|
||||
@@ -207,9 +215,9 @@ fn main() {
|
||||
}
|
||||
```
|
||||
|
||||
The expression in the `if` block is an integer and the expresion in the `else`
|
||||
block is a string. This can’t work, because variable bindings must have a
|
||||
single type. If we try to run this, we’ll get an error:
|
||||
If we try to run this, we’ll get an error. The `if` and `else` arms have value
|
||||
types that are incompatible, and Rust tells us exactly where to find the
|
||||
problem in our program:
|
||||
|
||||
```bash
|
||||
Compiling branches v0.1.0 (file:///projects/branches)
|
||||
@@ -223,20 +231,27 @@ src/main.rs:5 5
|
||||
src/main.rs:6 } else {
|
||||
src/main.rs:7 "six"
|
||||
src/main.rs:8 };
|
||||
src/main.rs:4:18: 8:6 help: run `rustc --explain E0308` to see a detailed explanation
|
||||
src/main.rs:4:18: 8:6 help: run `rustc --explain E0308` to see a detailed
|
||||
explanation
|
||||
error: aborting due to previous error
|
||||
Could not compile `branches`.
|
||||
```
|
||||
|
||||
The `if` and `else` arms have value types that are incompatible, and Rust tells
|
||||
us exactly where to find the problem in our program.
|
||||
The expression in the `if` block evaluates to an integer and the expresion in
|
||||
the `else` block evaluates to a string. This can’t work, because variable
|
||||
bindings 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
|
||||
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
|
||||
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.
|
||||
|
||||
### Repetition with Loops
|
||||
|
||||
It’s often useful to be able to execute a block of code more than one time. For
|
||||
this, Rust has several constructs called *loops*. A loop runs through the code
|
||||
inside it to the end and then starts immediately back at the beginning. To try
|
||||
out loops, let’s make a new project called `loops`.
|
||||
this, Rust has several *loops*. A loop runs through the code inside the loop
|
||||
body to the end and then starts immediately back at the beginning. To try out
|
||||
loops, let’s make a new project called `loops`.
|
||||
|
||||
There are three kinds of loops in Rust: `loop`, `while`, and `for`. Let’s dig
|
||||
in.
|
||||
@@ -280,16 +295,17 @@ received the signal to halt.
|
||||
|
||||
Fortunately, Rust provides another, more reliable way to break out of a loop.
|
||||
We can place the `break` keyword within the loop to tell the program when to
|
||||
stop executing the loop. Recall that we did this in the guessing game to exit
|
||||
the program when the user won the game by guessing the number correctly.
|
||||
stop executing the loop. Recall that we did this in the guessing game in
|
||||
Chapter 2 to exit the program when the user won the game by guessing the number
|
||||
correctly.
|
||||
|
||||
#### Conditional Loops With `while`
|
||||
|
||||
A useful thing that many programs do is 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
|
||||
ceases to be true, we call `break`, stopping the loop. This could be
|
||||
implemented with a combination of `loop`, `if`, `else`, and `break`; try to do
|
||||
that now if you'd like!
|
||||
implemented with a combination of `loop`, `if`, `else`, and `break`; you could
|
||||
try that now in a program, if you'd like.
|
||||
|
||||
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
|
||||
@@ -377,26 +393,28 @@ fn main() {
|
||||
|
||||
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
|
||||
bugs resulting from going beyond the end of the array or not going far enough
|
||||
and missing some items.
|
||||
bugs that might result from going beyond the end of the array or not going far
|
||||
enough and missing some items.
|
||||
|
||||
For example, in the previous code that uses the `while` loop, if we removed an
|
||||
item from the `a` array but forgot to update the condition to be `while index <
|
||||
item from the `a` array but forgot to update the condition to `while index <
|
||||
4`, our code would panic. Using the `for` loop means we would not need to
|
||||
remember to change any other code if we changed the number of values in the
|
||||
array.
|
||||
|
||||
If you're wondering about `iter` in this example, keep reading! We will cover
|
||||
method syntax generally in Chapter XX and iterators specifically in Chapter XX.
|
||||
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
|
||||
Chapter XX.
|
||||
|
||||
The safety and conciseness of `for` loops make them the most commonly used loop
|
||||
construct in Rust. Even in situations where you want to run some code a certain
|
||||
number of times, like our countdown example that used a `while` loop, most
|
||||
Rustaceans would use a `for` loop. The way to do that is using a `Range`, which
|
||||
is a type provided by the standard library that generates numbers starting from
|
||||
one number and ending before another number. 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:
|
||||
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
|
||||
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
|
||||
method we haven't yet talked about, `rev`, to reverse the range:
|
||||
|
||||
Filename: src/main.rs
|
||||
|
||||
@@ -411,5 +429,17 @@ fn main() {
|
||||
|
||||
That's a bit nicer, isn't it?
|
||||
|
||||
Now that you know how Rust does things that most other languages can do, let's
|
||||
talk about a concept that _doesn't_ commonly exist: ownership.
|
||||
## Summary
|
||||
|
||||
You made it! That was a big chapter: we covered variable bindings, scalar and
|
||||
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
|
||||
programs to do things like:
|
||||
|
||||
* Converting temperatures between Fahrenheit and Celsius.
|
||||
* Generate the nth Fibonacci number.
|
||||
* Print the lyrics to the Christmas carol *The Twelve Days of Christmas*,
|
||||
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_
|
||||
commonly exist in other programming languages: ownership.
|
||||
|
||||
@@ -19,7 +19,7 @@ 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
|
||||
through some examples, focusing on a very common data structure: strings.
|
||||
|
||||
PROD: START BOX
|
||||
<!-- PROD: START BOX -->
|
||||
|
||||
###### The Stack and the Heap
|
||||
|
||||
@@ -74,7 +74,7 @@ addresses. Once you understand ownership, you won't need to think about the
|
||||
stack and the heap very often, but knowing that managing heap data is why
|
||||
ownership exists can help explain why it works the way it does.
|
||||
|
||||
PROD: END BOX
|
||||
<!-- PROD: END BOX -->
|
||||
|
||||
### Ownership Rules
|
||||
|
||||
|
||||
Reference in New Issue
Block a user