mirror of
https://github.com/rust-lang/book.git
synced 2026-11-30 19:44:33 -06:00
Forward porting changes
This commit is contained in:
@@ -9,8 +9,6 @@ Specifically, you’ll learn about variables, 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 -->
|
||||
|
||||
> ### Keywords
|
||||
>
|
||||
> The Rust language has a set of *keywords* that have been reserved for use by
|
||||
@@ -20,5 +18,3 @@ them early will give you a strong core to start from.
|
||||
> programs; a few have no current functionality associated with them but have
|
||||
> been reserved for functionality that might be added to Rust in the future. You
|
||||
> can find a list of the keywords in Appendix A.
|
||||
|
||||
<!-- PROD: END BOX -->
|
||||
|
||||
@@ -28,8 +28,6 @@ Save and run the program using `cargo run`. You should receive an error
|
||||
message, as shown in this output:
|
||||
|
||||
```text
|
||||
$ cargo run
|
||||
Compiling variables v0.0.1 (file:///projects/variables)
|
||||
error[E0384]: re-assignment of immutable variable `x`
|
||||
--> src/main.rs:4:5
|
||||
|
|
||||
@@ -98,44 +96,51 @@ variables.
|
||||
There are multiple trade-offs to consider, in addition to the prevention of
|
||||
bugs. For example, in cases where you’re using large data structures, mutating
|
||||
an instance in place may be faster than copying and returning newly allocated
|
||||
instances. With smaller data structures, always creating new instances and
|
||||
writing in a more functional programming style may be easier to reason about,
|
||||
so the lower performance penalty might be worth it to gain that clarity.
|
||||
instances. With smaller data structures, creating new instances and writing in
|
||||
a more functional programming style may be easier to reason about, so the lower
|
||||
performance might be a worthwhile penalty for gaining that clarity.
|
||||
|
||||
### Differences Between Variables and Constants
|
||||
|
||||
Not being able to change the value of a variable might have reminded you of
|
||||
another programming concept that most languages have: *constants*. Constants
|
||||
are also values bound to a name that are not allowed to change, but there are a
|
||||
few differences between constants and variables. First, using `mut` with
|
||||
constants is not allowed: constants aren't only immutable by default, they're
|
||||
always immutable. Constants are declared using the `const` keyword instead of
|
||||
the `let` keyword, and the type of the value *must* be annotated. We're about
|
||||
to cover types and type annotations in the next section, “Data Types,” so don't
|
||||
worry about the details right now. Constants can be declared in any scope,
|
||||
including the global scope, which makes them useful for a value that many parts
|
||||
of your code need to know about. The last difference is that constants may only
|
||||
be set to a constant expression, not the result of a function call or any other
|
||||
value that could only be used at runtime.
|
||||
Being unable to change the value of a variable might have reminded you of
|
||||
another programming concept that most other languages have: *constants*. Like
|
||||
immutable variables, constants are also values that are bound to a name and
|
||||
are not allowed to change, but there are a few differences between constants
|
||||
and variables.
|
||||
|
||||
First, we aren’t allowed to use `mut` with constants: constants aren't only
|
||||
immutable by default, they're always immutable.
|
||||
|
||||
We declare constants using the `const` keyword instead of the `let` keyword,
|
||||
and the type of the value *must* be annotated. We're about to cover types and
|
||||
type annotations in the next section, “Data Types,” so don't worry about the
|
||||
details right now, just know that we must always annotate the type.
|
||||
|
||||
Constants can be declared in any scope, including the global scope, which makes
|
||||
them useful for values that many parts of code need to know about.
|
||||
|
||||
The last difference is that constants may only be set to a constant expression,
|
||||
not the result of a function call or any other value that could only be
|
||||
computed at runtime.
|
||||
|
||||
Here's an example of a constant declaration where the constant's name is
|
||||
`MAX_POINTS` and its value is set to 100,000. Rust constant naming convention
|
||||
is to use all upper case with underscores between words:
|
||||
`MAX_POINTS` and its value is set to 100,000. (Rust constant naming convention
|
||||
is to use all upper case with underscores between words):
|
||||
|
||||
```
|
||||
```rust
|
||||
const MAX_POINTS: u32 = 100_000;
|
||||
```
|
||||
|
||||
Constants are valid for the entire lifetime of a program, within the scope they
|
||||
were declared in. That makes constants useful for values in your application
|
||||
Constants are valid for the entire time a program runs, within the scope they
|
||||
were declared in, making them a useful choice for values in your application
|
||||
domain that multiple part of the program might need to know about, such as the
|
||||
maximum number of points any player of a game is allowed to earn or the number
|
||||
of seconds in a year.
|
||||
maximum number of points any player of a game is allowed to earn or the speed
|
||||
of light.
|
||||
|
||||
Documenting hardcoded values used throughout your program by naming them as
|
||||
constants is useful to convey the meaning of that value to future maintainers
|
||||
of the code. It also helps to have only one place in your code that you would
|
||||
need to change if the hardcoded value needed to be updated in the future.
|
||||
Naming hardcoded values used throughout your program as constants is useful in
|
||||
conveying the meaning of that value to future maintainers of the code. It also
|
||||
helps to have only one place in your code you would need to change if the
|
||||
hardcoded value needed to be updated in the future.
|
||||
|
||||
### Shadowing
|
||||
|
||||
@@ -212,7 +217,7 @@ error[E0308]: mismatched types
|
||||
| ^^^^^^^^^^^^ expected &str, found usize
|
||||
|
|
||||
= note: expected type `&str`
|
||||
= note: found type `usize`
|
||||
found type `usize`
|
||||
```
|
||||
|
||||
Now that we’ve explored how variables work, let’s look at more data types they
|
||||
|
||||
@@ -22,10 +22,10 @@ possible type we want to use:
|
||||
|
||||
```text
|
||||
error[E0282]: unable to infer enough type information about `_`
|
||||
--> src/main.rs:2:5
|
||||
--> src/main.rs:2:9
|
||||
|
|
||||
2 | let guess = "42".parse().expect("Not a number!");
|
||||
| ^^^^^ cannot infer type for `_`
|
||||
2 | let guess = "42".parse().expect("Not a number!");
|
||||
| ^^^^^ cannot infer type for `_`
|
||||
|
|
||||
= note: type annotations or generic parameter binding required
|
||||
```
|
||||
@@ -44,9 +44,10 @@ work in Rust.
|
||||
An *integer* is a number without a fractional component. We used one integer
|
||||
type earlier 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`,
|
||||
as opposed to a `u` for unsigned) for a 32-bit system. Table 3-1 shows the
|
||||
built-in integer types in Rust. Each variant in the Signed and Unsigned columns
|
||||
(for example, *i32*) can be used to declare the type of an integer value.
|
||||
as opposed to a `u` for unsigned) that takes up 32 bits of space. Table 3-1
|
||||
shows the built-in integer types in Rust. Each variant in the Signed and
|
||||
Unsigned columns (for example, *i32*) can be used to declare the type of an
|
||||
integer value.
|
||||
|
||||
<span class="caption">Table 3-1: Integer Types in Rust</span>
|
||||
|
||||
@@ -334,8 +335,9 @@ the array? Say we change the example to the following:
|
||||
```rust,ignore
|
||||
fn main() {
|
||||
let a = [1, 2, 3, 4, 5];
|
||||
let index = 10;
|
||||
|
||||
let element = a[10];
|
||||
let element = a[index];
|
||||
|
||||
println!("The value of element is: {}", element);
|
||||
}
|
||||
@@ -348,9 +350,8 @@ $ 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
|
||||
10', src/main.rs:6
|
||||
note: Run with `RUST_BACKTRACE=1` for a backtrace.
|
||||
error: Process didn't exit successfully: `target/debug/arrays` (exit code: 101)
|
||||
```
|
||||
|
||||
The compilation didn’t produce any errors, but the program results in a
|
||||
|
||||
@@ -56,8 +56,8 @@ Functions can also be defined to have *parameters*, which are special variables
|
||||
that are part of a function's signature. When a function has parameters, we can
|
||||
provide it with concrete values for those parameters. Technically, the concrete
|
||||
values are called *arguments*, but in casual conversation people tend to use
|
||||
the words "parameter" and "argument" interchangeably for either the variables in
|
||||
a function's definition or the concrete values passed in when you call a
|
||||
the words “parameter” and “argument” interchangeably for either the variables
|
||||
in a function's definition or the concrete values passed in when you call a
|
||||
function.
|
||||
|
||||
The following rewritten version of `another_function` shows what parameters
|
||||
@@ -112,7 +112,7 @@ fn another_function(x: i32, y: i32) {
|
||||
|
||||
This example creates a function with two parameters, both of which are `i32`
|
||||
types. The function then prints out the values in both of its parameters. Note
|
||||
that function parameters don't all need to be the same type - they just happen
|
||||
that function parameters don't all need to be the same type, they just happen
|
||||
to be in this example.
|
||||
|
||||
Let’s try running this code. Replace the program currently in your *function*
|
||||
@@ -127,8 +127,8 @@ The value of x is: 5
|
||||
The value of y is: 6
|
||||
```
|
||||
|
||||
Because we called the function with `5` as the value for `x` and `6` as the
|
||||
value for `y`, the two strings are printed using those values.
|
||||
Because we called the function with `5` as the value for `x` and `6` is passed
|
||||
as the value for `y`, the two strings are printed with these values.
|
||||
|
||||
### Function Bodies
|
||||
|
||||
@@ -316,12 +316,17 @@ fn plus_one(x: i32) -> i32 {
|
||||
Running this code produces an error, as follows:
|
||||
|
||||
```text
|
||||
error[E0269]: not all control paths return a value
|
||||
--> src/main.rs:7:1
|
||||
error[E0308]: mismatched types
|
||||
--> src/main.rs:7:28
|
||||
|
|
||||
7 | fn plus_one(x: i32) -> i32 {
|
||||
| ^
|
||||
7 | fn plus_one(x: i32) -> i32 {
|
||||
| ____________________________^ starting here...
|
||||
8 | | x + 1;
|
||||
9 | | }
|
||||
| |_^ ...ending here: expected i32, found ()
|
||||
|
|
||||
= note: expected type `i32`
|
||||
found type `()`
|
||||
help: consider removing this semicolon:
|
||||
--> src/main.rs:8:10
|
||||
|
|
||||
@@ -329,9 +334,10 @@ help: consider removing this semicolon:
|
||||
| ^
|
||||
```
|
||||
|
||||
The main error message, “not all control paths return a value,” reveals the
|
||||
core 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. Therefore,
|
||||
nothing is returned, which contradicts the function definition and results in
|
||||
an error. In this output, Rust provides a message to possibly help rectify this
|
||||
issue: it suggests removing the semicolon, which would fix the error.
|
||||
The main error message, “mismatched types,” reveals the core 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, which is expressed by `()`,
|
||||
the empty tuple. Therefore, nothing is returned, which contradicts the function
|
||||
definition and results in an error. In this output, Rust provides a message to
|
||||
possibly help rectify this issue: it suggests removing the semicolon, which
|
||||
would fix the error.
|
||||
|
||||
@@ -29,6 +29,8 @@ fn main() {
|
||||
}
|
||||
```
|
||||
|
||||
<!-- NEXT PARAGRAPH WRAPPED WEIRD INTENTIONALLY SEE #199 -->
|
||||
|
||||
All `if` expressions start with the keyword `if`, which is followed by a
|
||||
condition. In this case, the condition checks whether or not the variable
|
||||
`number` has a value less than 5. The block of code we want to execute if the
|
||||
@@ -87,7 +89,6 @@ The `if` condition evaluates to a value of `3` this time, and Rust throws an
|
||||
error:
|
||||
|
||||
```text
|
||||
Compiling branches v0.1.0 (file:///projects/branches)
|
||||
error[E0308]: mismatched types
|
||||
--> src/main.rs:4:8
|
||||
|
|
||||
@@ -95,10 +96,7 @@ error[E0308]: mismatched types
|
||||
| ^^^^^^ expected bool, found integral variable
|
||||
|
|
||||
= note: expected type `bool`
|
||||
= note: found type `{integer}`
|
||||
|
||||
error: aborting due to previous error
|
||||
Could not compile `branches`.
|
||||
found type `{integer}`
|
||||
```
|
||||
|
||||
The error indicates that Rust expected a `bool` but got an integer. Rust will
|
||||
@@ -223,20 +221,24 @@ fn main() {
|
||||
}
|
||||
```
|
||||
|
||||
When we run this code, we’ll get an error. The `if` and `else` arms have value
|
||||
types that are incompatible, and Rust indicates exactly where to find the
|
||||
When we try to run this code, we’ll get an error. The `if` and `else` arms have
|
||||
value types that are incompatible, and Rust indicates exactly where to find the
|
||||
problem in the program:
|
||||
|
||||
```text
|
||||
Compiling branches v0.1.0 (file:///projects/branches)
|
||||
error[E0308]: if and else have incompatible types
|
||||
--> src/main.rs:4:18
|
||||
|
|
||||
4 | let number = if condition {
|
||||
| ^ expected integral variable, found reference
|
||||
4 | let number = if condition {
|
||||
| __________________^ starting here...
|
||||
5 | | 5
|
||||
6 | | } else {
|
||||
7 | | "six"
|
||||
8 | | };
|
||||
| |_____^ ...ending here: expected integral variable, found reference
|
||||
|
|
||||
= note: expected type `{integer}`
|
||||
= note: found type `&’static str`
|
||||
found type `&'static str`
|
||||
```
|
||||
|
||||
The expression in the `if` block evaluates to an integer, and the expression in
|
||||
@@ -377,9 +379,9 @@ will reach a value of `5` at some point, the loop stops executing before trying
|
||||
to fetch a sixth value from the array.
|
||||
|
||||
But this approach is error prone; we could cause the program to panic if the
|
||||
index length is incorrect. It’s also slow, because the compiler adds
|
||||
runtime code to perform the conditional check on every element on every
|
||||
iteration through the loop.
|
||||
index length is incorrect. It’s also slow, because the compiler adds runtime
|
||||
code to perform the conditional check on every element on every iteration
|
||||
through the loop.
|
||||
|
||||
As a more efficient alternative, you can use a `for` loop and execute some code
|
||||
for each item in a collection. A `for` loop looks like this:
|
||||
|
||||
Reference in New Issue
Block a user