mirror of
https://github.com/rust-lang/book.git
synced 2026-12-04 13:24:55 -06:00
Link more cross references
This commit is contained in:
@@ -33,8 +33,8 @@ it can’t provide appropriate default behavior for you.
|
||||
The list of derivable traits provided in this appendix is not comprehensive:
|
||||
libraries can implement `derive` for their own traits, making the list of
|
||||
traits you can use `derive` with truly open-ended. Implementing `derive`
|
||||
involves using a procedural macro, which is covered in the “Macros” section of
|
||||
Chapter 19.
|
||||
involves using a procedural macro, which is covered in the
|
||||
[“Macros”][macros]<!-- ignore --> section of Chapter 19.
|
||||
|
||||
### `Debug` for Programmer Output
|
||||
|
||||
@@ -184,3 +184,4 @@ ch05-01-defining-structs.html#creating-instances-from-other-instances-with-struc
|
||||
ch04-01-what-is-ownership.html#stack-only-data-copy
|
||||
[ways-variables-and-data-interact-clone]:
|
||||
ch04-01-what-is-ownership.html#ways-variables-and-data-interact-clone
|
||||
[macros]: ch19-06-macros.html#macros
|
||||
|
||||
@@ -762,8 +762,9 @@ comparison will be between two values of the same type!
|
||||
The call to `parse` could easily cause an error. If, for example, the string
|
||||
contained `A👍%`, there would be no way to convert that to a number. Because it
|
||||
might fail, the `parse` method returns a `Result` type, much as the `read_line`
|
||||
method does (discussed earlier in “Handling Potential Failure with the Result
|
||||
Type”). We’ll treat this `Result` the same way by using the `expect` method
|
||||
method does (discussed earlier in [“Handling Potential Failure with the
|
||||
`Result` Type”](#handling-potential-failure-with-the-result-type)<!-- ignore
|
||||
-->). We’ll treat this `Result` the same way by using the `expect` method
|
||||
again. If `parse` returns an `Err` `Result` variant because it couldn’t create
|
||||
a number from the string, the `expect` call will crash the game and print the
|
||||
message we give it. If `parse` can successfully convert the string to a number,
|
||||
|
||||
@@ -115,8 +115,9 @@ immutable by default—they’re always immutable.
|
||||
|
||||
You 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 you must always annotate the type.
|
||||
type annotations in the next section, [“Data Types,”][data-types]<!-- ignore
|
||||
--> so don’t worry about the details right now. Just know that you 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.
|
||||
@@ -231,3 +232,4 @@ can have.
|
||||
|
||||
[comparing-the-guess-to-the-secret-number]:
|
||||
ch02-00-guessing-game-tutorial.html#comparing-the-guess-to-the-secret-number
|
||||
[data-types]: ch03-02-data-types.html#data-types
|
||||
|
||||
@@ -214,7 +214,8 @@ Korean characters; emoji; and zero-width spaces are all valid `char` values in
|
||||
Rust. Unicode Scalar Values range from `U+0000` to `U+D7FF` and `U+E000` to
|
||||
`U+10FFFF` inclusive. However, a “character” isn’t really a concept in Unicode,
|
||||
so your human intuition for what a “character” is may not match up with what a
|
||||
`char` is in Rust. We’ll discuss this topic in detail in “Strings” in Chapter 8.
|
||||
`char` is in Rust. We’ll discuss this topic in detail in [“Storing UTF-8
|
||||
Encoded Text with Strings”][strings]<!-- ignore --> in Chapter 8.
|
||||
|
||||
### Compound Types
|
||||
|
||||
@@ -401,3 +402,4 @@ continuing. Chapter 9 discusses more of Rust’s error handling.
|
||||
[comparing-the-guess-to-the-secret-number]:
|
||||
ch02-00-guessing-game-tutorial.html#comparing-the-guess-to-the-secret-number
|
||||
[control-flow]: ch03-05-control-flow.html#control-flow
|
||||
[strings]: ch08-02-strings.html#storing-utf-8-encoded-text-with-strings
|
||||
|
||||
@@ -165,8 +165,8 @@ The double colon (`::`) is an operator that allows us to namespace this
|
||||
particular `from` function under the `String` type rather than using some sort
|
||||
of name like `string_from`. We’ll discuss this syntax more in the [“Method
|
||||
Syntax”][method-syntax]<!-- ignore --> section of Chapter 5 and when we talk
|
||||
about namespacing with modules in “Paths for Referring to an Item in the Module
|
||||
Tree” in Chapter 7.
|
||||
about namespacing with modules in [“Paths for Referring to an Item in the
|
||||
Module Tree”][paths-module-tree]<!-- ignore --> in Chapter 7.
|
||||
|
||||
This kind of string *can* be mutated:
|
||||
|
||||
@@ -556,3 +556,4 @@ common. Luckily for us, Rust has a feature for this concept, called
|
||||
[data-types]: ch03-02-data-types.html#data-types
|
||||
[derivable-traits]: appendix-03-derivable-traits.html#derivable-traits
|
||||
[method-syntax]: ch05-03-method-syntax.html#method-syntax
|
||||
[paths-module-tree]: ch07-02-modules-and-use-to-control-scope-and-privacy.html#paths-for-referring-to-an-item-in-the-module-tree
|
||||
|
||||
@@ -217,8 +217,8 @@ let slice = &s[..];
|
||||
> boundaries. If you attempt to create a string slice in the middle of a
|
||||
> multibyte character, your program will exit with an error. For the purposes
|
||||
> of introducing string slices, we are assuming ASCII only in this section; a
|
||||
> more thorough discussion of UTF-8 handling is in the “Storing UTF-8 Encoded
|
||||
> Text with Strings” section of Chapter 8.
|
||||
> more thorough discussion of UTF-8 handling is in the [“Storing UTF-8 Encoded
|
||||
> Text with Strings”][strings]<!-- ignore --> section of Chapter 8.
|
||||
|
||||
With all this information in mind, let’s rewrite `first_word` to return a
|
||||
slice. The type that signifies “string slice” is written as `&str`:
|
||||
@@ -403,3 +403,5 @@ 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’ll talk about
|
||||
these concepts further throughout the rest of the book. Let’s move on to
|
||||
Chapter 5 and look at grouping pieces of data together in a `struct`.
|
||||
|
||||
[strings]: ch08-02-strings.html#storing-utf-8-encoded-text-with-strings
|
||||
|
||||
@@ -69,11 +69,12 @@ Listing 7-1. We then defined two modules within the `sound` module named
|
||||
`instrument` and `voice`. The `instrument` module has another module defined
|
||||
within it, `woodwind`, and that module contains a function named `clarinet`.
|
||||
|
||||
We mentioned in the “Packages and Crates for Making Libraries and Executables”
|
||||
section that *src/main.rs* and *src/lib.rs* are called *crate roots*. They are
|
||||
called crate roots because the contents of either of these two files form a
|
||||
module named `crate` at the root of the crate’s module tree. So in Listing 7-2,
|
||||
we have a module tree that looks like Listing 7-3:
|
||||
We mentioned in the [“Packages and Crates for Making Libraries and
|
||||
Executables”][packages]<!-- ignore --> section that *src/main.rs* and
|
||||
*src/lib.rs* are called *crate roots*. They are called crate roots because the
|
||||
contents of either of these two files form a module named `crate` at the root
|
||||
of the crate’s module tree. So in Listing 7-2, we have a module tree that looks
|
||||
like Listing 7-3:
|
||||
|
||||
```text
|
||||
crate
|
||||
@@ -781,9 +782,9 @@ available to our project.
|
||||
|
||||
Then, to bring `rand` definitions into the scope of our package, we added a
|
||||
`use` line starting with the name of the package, `rand`, and listing the items
|
||||
we wanted to bring into scope. Recall that in the “Generating a Random Number”
|
||||
section in Chapter 2, we brought the `Rng` trait into scope and called the
|
||||
`rand::thread_rng` function:
|
||||
we wanted to bring into scope. Recall that in the [“Generating a Random
|
||||
Number”][rand]<!-- ignore --> section in Chapter 2, we brought the `Rng` trait
|
||||
into scope and called the `rand::thread_rng` function:
|
||||
|
||||
```rust,ignore
|
||||
use rand::Rng;
|
||||
@@ -890,11 +891,11 @@ Be careful with using the glob operator! It makes it harder to tell what names
|
||||
are in scope and where a name your program uses was defined.
|
||||
|
||||
The glob operator is often used when testing to bring everything under test
|
||||
into the `tests` module; we’ll talk about that in the “How to Write Tests”
|
||||
section of Chapter 11. The glob operator is also sometimes used as part of the
|
||||
prelude pattern; see [the standard library
|
||||
documentation](../std/prelude/index.html#other-preludes) for more
|
||||
information on that pattern.
|
||||
into the `tests` module; we’ll talk about that in the [“How to Write
|
||||
Tests”][writing-tests]<!-- ignore --> section of Chapter 11. The glob operator
|
||||
is also sometimes used as part of the prelude pattern; see [the standard
|
||||
library documentation](../std/prelude/index.html#other-preludes)<!-- ignore -->
|
||||
for more information on that pattern.
|
||||
|
||||
### Separating Modules into Different Files
|
||||
|
||||
@@ -978,3 +979,7 @@ choose to make definitions public by adding the `pub` keyword.
|
||||
|
||||
Next, we’ll look at some collection data structures in the standard library
|
||||
that you can use in your nice, neat code.
|
||||
|
||||
[packages]: ch07-01-packages-and-crates-for-making-libraries-and-executables.html#packages-and-crates-for-making-libraries-and-executables
|
||||
[rand]: ch02-00-guessing-game-tutorial.html#generating-a-random-number
|
||||
[writing-tests]: ch11-01-writing-tests.html#how-to-write-tests
|
||||
|
||||
@@ -6,8 +6,8 @@ interpret and respond to. For example, if you try to open a file and that
|
||||
operation fails because the file doesn’t exist, you might want to create the
|
||||
file instead of terminating the process.
|
||||
|
||||
Recall from “[Handling Potential Failure with the `Result`
|
||||
Type][handle_failure]<!-- ignore -->” in Chapter 2 that the `Result` enum is
|
||||
Recall from [“Handling Potential Failure with the `Result`
|
||||
Type”][handle_failure]<!-- ignore --> in Chapter 2 that the `Result` enum is
|
||||
defined as having two variants, `Ok` and `Err`, as follows:
|
||||
|
||||
[handle_failure]: ch02-00-guessing-game-tutorial.html#handling-potential-failure-with-the-result-type
|
||||
|
||||
@@ -405,8 +405,9 @@ fn returns_summarizable(switch: bool) -> impl Summary {
|
||||
|
||||
Here, we try to return either a `NewsArticle` or a `Tweet`. This cannot work,
|
||||
due to restrictions around how `impl Trait` works. To write this code, you’ll
|
||||
have to wait until the “Using Trait Objects that Allow for Values of Different
|
||||
Types” section of Chapter 17.
|
||||
have to wait until the [“Using Trait Objects That Allow for Values of Different
|
||||
Types”][using-trait-objects-that-allow-for-values-of-different-types]<!--
|
||||
ignore --> section of Chapter 17.
|
||||
|
||||
### Fixing the `largest` Function with Trait Bounds
|
||||
|
||||
@@ -605,3 +606,5 @@ lifetimes do that.
|
||||
|
||||
[stack-only-data-copy]:
|
||||
ch04-01-what-is-ownership.html#stack-only-data-copy
|
||||
[using-trait-objects-that-allow-for-values-of-different-types]:
|
||||
ch17-02-trait-objects.html#using-trait-objects-that-allow-for-values-of-different-types
|
||||
|
||||
@@ -118,8 +118,9 @@ The next part of the test output, which starts with `Doc-tests adder`, is for
|
||||
the results of any documentation tests. We don’t have any documentation tests
|
||||
yet, but Rust can compile any code examples that appear in our API
|
||||
documentation. This feature helps us keep our docs and our code in sync! We’ll
|
||||
discuss how to write documentation tests in the “Documentation Comments”
|
||||
section of Chapter 14. For now, we’ll ignore the `Doc-tests` output.
|
||||
discuss how to write documentation tests in the [“Making Useful Documentation
|
||||
Comments”][doc-comments]<!-- ignore --> section of Chapter 14. For now, we’ll
|
||||
ignore the `Doc-tests` output.
|
||||
|
||||
Let’s change the name of our test to see how that changes the test output.
|
||||
Change the `it_works` function to a different name, such as `exploration`, like
|
||||
@@ -281,10 +282,11 @@ larger rectangle can indeed hold a smaller rectangle</span>
|
||||
|
||||
Note that we’ve added a new line inside the `tests` module: `use super::*;`.
|
||||
The `tests` module is a regular module that follows the usual visibility rules
|
||||
we covered in Chapter 7 in the “Modules as the Privacy Boundary” section.
|
||||
Because the `tests` module is an inner module, we need to bring the code under
|
||||
test in the outer module into the scope of the inner module. We use a glob here
|
||||
so anything we define in the outer module is available to this `tests` module.
|
||||
we covered in Chapter 7 in the [“Modules as the Privacy
|
||||
Boundary”][modules-as-privacy-boundary]<!-- ignore --> section. Because the
|
||||
`tests` module is an inner module, we need to bring the code under test in the
|
||||
outer module into the scope of the inner module. We use a glob here so anything
|
||||
we define in the outer module is available to this `tests` module.
|
||||
|
||||
We’ve named our test `larger_can_hold_smaller`, and we’ve created the two
|
||||
`Rectangle` instances that we need. Then we called the `assert!` macro and
|
||||
@@ -497,8 +499,8 @@ those types are equal or not equal. You’ll need to implement `Debug` to print
|
||||
the values when the assertion fails. Because both traits are derivable traits,
|
||||
as mentioned in Listing 5-12 in Chapter 5, this is usually as straightforward
|
||||
as adding the `#[derive(PartialEq, Debug)]` annotation to your struct or enum
|
||||
definition. See Appendix C, “Derivable Traits,” for more details about these
|
||||
and other derivable traits.
|
||||
definition. See Appendix C, [“Derivable Traits,”][derivable-traits]<!-- ignore
|
||||
--> for more details about these and other derivable traits.
|
||||
|
||||
### Adding Custom Failure Messages
|
||||
|
||||
@@ -838,3 +840,6 @@ test`.
|
||||
ch08-02-strings.html#concatenation-with-the--operator-or-the-format-macro
|
||||
[controlling-how-tests-are-run]:
|
||||
ch11-02-running-tests.html#controlling-how-tests-are-run
|
||||
[derivable-traits]: appendix-03-derivable-traits.html#derivable-traits
|
||||
[doc-comments]: ch14-02-publishing-to-crates-io.html#making-useful-documentation-comments
|
||||
[modules-as-privacy-boundary]: ch07-02-modules-and-use-to-control-scope-and-privacy.html#modules-as-the-privacy-boundary
|
||||
|
||||
@@ -214,11 +214,12 @@ separate code into modules and files.
|
||||
|
||||
The different behavior of files in the *tests* directory is most noticeable
|
||||
when you have a set of helper functions that would be useful in multiple
|
||||
integration test files and you try to follow the steps in the “Separating
|
||||
Modules into Different Files” section of Chapter 7 to extract them into a
|
||||
common module. For example, if we create *tests/common.rs* and place a function
|
||||
named `setup` in it, we can add some code to `setup` that we want to call from
|
||||
multiple test functions in multiple test files:
|
||||
integration test files and you try to follow the steps in the [“Separating
|
||||
Modules into Different Files”][separating-modules-into-files]<!-- ignore -->
|
||||
section of Chapter 7 to extract them into a common module. For example, if we
|
||||
create *tests/common.rs* and place a function named `setup` in it, we can add
|
||||
some code to `setup` that we want to call from multiple test functions in
|
||||
multiple test files:
|
||||
|
||||
<span class="filename">Filename: tests/common.rs</span>
|
||||
|
||||
@@ -322,3 +323,6 @@ reduce logic bugs having to do with how your code is expected to behave.
|
||||
|
||||
Let’s combine the knowledge you learned in this chapter and in previous
|
||||
chapters to work on a project!
|
||||
|
||||
[separating-modules-into-files]:
|
||||
ch07-02-modules-and-use-to-control-scope-and-privacy.html#separating-modules-into-different-files
|
||||
|
||||
+6
-3
@@ -23,9 +23,10 @@ time because the data is copied around on the stack. To improve performance in
|
||||
this situation, we can store the large amount of data on the heap in a box.
|
||||
Then, only the small amount of pointer data is copied around on the stack,
|
||||
while the data it references stays in one place on the heap. The third case is
|
||||
known as a *trait object*, and Chapter 17 devotes an entire section, “Using
|
||||
Trait Objects That Allow for Values of Different Types,” just to that topic. So
|
||||
what you learn here you’ll apply again in Chapter 17!
|
||||
known as a *trait object*, and Chapter 17 devotes an entire section, [“Using
|
||||
Trait Objects That Allow for Values of Different Types,”][trait-objects]<!--
|
||||
ignore --> just to that topic. So what you learn here you’ll apply again in
|
||||
Chapter 17!
|
||||
|
||||
### Using a `Box<T>` to Store Data on the Heap
|
||||
|
||||
@@ -279,3 +280,5 @@ up as well because of the `Drop` trait implementation. Let’s explore these two
|
||||
traits in more detail. These two traits will be even more important to the
|
||||
functionality provided by the other smart pointer types we’ll discuss in the
|
||||
rest of this chapter.
|
||||
|
||||
[trait-objects]: ch17-02-trait-objects.html#using-trait-objects-that-allow-for-values-of-different-types
|
||||
|
||||
+4
-1
@@ -183,7 +183,8 @@ At each point in the program where the reference count changes, we print the
|
||||
reference count, which we can get by calling the `Rc::strong_count` function.
|
||||
This function is named `strong_count` rather than `count` because the `Rc<T>`
|
||||
type also has a `weak_count`; we’ll see what `weak_count` is used for in the
|
||||
“Preventing Reference Cycles” section.
|
||||
[“Preventing Reference Cycles: Turning an `Rc<T>` into a
|
||||
`Weak<T>`”][preventing-ref-cycles]<!-- ignore --> section.
|
||||
|
||||
This code prints the following:
|
||||
|
||||
@@ -215,3 +216,5 @@ and inconsistencies. But being able to mutate data is very useful! In the next
|
||||
section, we’ll discuss the interior mutability pattern and the `RefCell<T>`
|
||||
type that you can use in conjunction with an `Rc<T>` to work with this
|
||||
immutability restriction.
|
||||
|
||||
[preventing-ref-cycles]: ch15-06-reference-cycles.html#preventing-reference-cycles-turning-an-rct-into-a-weakt
|
||||
|
||||
@@ -85,3 +85,6 @@ go forth and make your programs concurrent, fearlessly!
|
||||
Next, we’ll talk about idiomatic ways to model problems and structure solutions
|
||||
as your Rust programs get bigger. In addition, we’ll discuss how Rust’s idioms
|
||||
relate to those you might be familiar with from object-oriented programming.
|
||||
|
||||
[sharing-a-mutext-between-multiple-threads]:
|
||||
ch16-03-shared-state.html#sharing-a-mutext-between-multiple-threads
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
## Using Trait Objects that Allow for Values of Different Types
|
||||
## Using Trait Objects That Allow for Values of Different Types
|
||||
|
||||
In Chapter 8, we mentioned that one limitation of vectors is that they can
|
||||
store elements of only one type. We created a workaround in Listing 8-10 where
|
||||
@@ -45,11 +45,11 @@ implements the trait we specify. We create a trait object by specifying some
|
||||
sort of pointer, such as a `&` reference or a `Box<T>` smart pointer, and then
|
||||
specifying the relevant trait, and add a `dyn` keyword. (We’ll talk about the
|
||||
reason trait objects must use a pointer in Chapter 19 in the section
|
||||
“Dynamically Sized Types & Sized”.) We can use trait objects in place of a
|
||||
generic or concrete type. Wherever we use a trait object, Rust’s type system
|
||||
will ensure at compile time that any value used in that context will
|
||||
implement the trait object’s trait. Consequently, we don’t need to know all
|
||||
the possible types at compile time.
|
||||
[“Dynamically Sized Types and the `Sized` Trait.”][dynamically-sized]<!--
|
||||
ignore -->) We can use trait objects in place of a generic or concrete type.
|
||||
Wherever we use a trait object, Rust’s type system will ensure at compile time
|
||||
that any value used in that context will implement the trait object’s trait.
|
||||
Consequently, we don’t need to know all the possible types at compile time.
|
||||
|
||||
We’ve mentioned that in Rust, we refrain from calling structs and enums
|
||||
“objects” to distinguish them from other languages’ objects. In a struct or
|
||||
@@ -421,3 +421,4 @@ you’re interested in more details on object safety, see [Rust RFC 255].
|
||||
|
||||
[performance-of-code-using-generics]:
|
||||
ch10-01-syntax.html#performance-of-code-using-generics
|
||||
[dynamically-sized]: ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait
|
||||
|
||||
@@ -403,9 +403,10 @@ move `state` out of the borrowed `&self` of the function parameter.
|
||||
We then call the `unwrap` method, which we know will never panic, because we
|
||||
know the methods on `Post` ensure that `state` will always contain a `Some`
|
||||
value when those methods are done. This is one of the cases we talked about in
|
||||
the “Cases When You Have More Information Than the Compiler” section of Chapter
|
||||
9 when we know that a `None` value is never possible, even though the compiler
|
||||
isn’t able to understand that.
|
||||
the [“Cases In Which You Have More Information Than the
|
||||
Compiler”][more-info-than-rustc]<!-- ignore --> section of Chapter 9 when we
|
||||
know that a `None` value is never possible, even though the compiler isn’t able
|
||||
to understand that.
|
||||
|
||||
At this point, when we call `content` on the `&Box<dyn State>`, deref coercion will
|
||||
take effect on the `&` and the `Box` so the `content` method will ultimately be
|
||||
@@ -507,7 +508,7 @@ and `approve` methods on `Post`. Both methods delegate to the implementation of
|
||||
the same method on the value in the `state` field of `Option` and set the new
|
||||
value of the `state` field to the result. If we had a lot of methods on `Post`
|
||||
that followed this pattern, we might consider defining a macro to eliminate the
|
||||
repetition (see the “Macros” section in Chapter 19).
|
||||
repetition (see the [“Macros”][macros]<!-- ignore --> section in Chapter 19).
|
||||
|
||||
By implementing the state pattern exactly as it’s defined for object-oriented
|
||||
languages, we’re not taking as full advantage of Rust’s strengths as we could.
|
||||
@@ -723,3 +724,6 @@ option.
|
||||
Next, we’ll look at patterns, which are another of Rust’s features that enable
|
||||
lots of flexibility. We’ve looked at them briefly throughout the book but
|
||||
haven’t seen their full capability yet. Let’s go!
|
||||
|
||||
[more-info-than-rustc]: ch09-03-to-panic-or-not-to-panic.html#cases-in-which-you-have-more-information-than-the-compiler
|
||||
[macros]: ch19-06-macros.html#macros
|
||||
|
||||
@@ -156,10 +156,11 @@ a data race. Be careful!
|
||||
|
||||
With all of these dangers, why would you ever use raw pointers? One major use
|
||||
case is when interfacing with C code, as you’ll see in the next section,
|
||||
“Calling an Unsafe Function or Method.” Another case is when building up safe
|
||||
abstractions that the borrow checker doesn’t understand. We’ll introduce unsafe
|
||||
functions and then look at an example of a safe abstraction that uses unsafe
|
||||
code.
|
||||
[“Calling an Unsafe Function or
|
||||
Method.”](#calling-an-unsafe-function-or-method)<!-- ignore --> Another case is
|
||||
when building up safe abstractions that the borrow checker doesn’t understand.
|
||||
We’ll introduce unsafe functions and then look at an example of a safe
|
||||
abstraction that uses unsafe code.
|
||||
|
||||
### Calling an Unsafe Function or Method
|
||||
|
||||
@@ -440,12 +441,14 @@ fn main() {
|
||||
<span class="caption">Listing 19-9: Defining and using an immutable static
|
||||
variable</span>
|
||||
|
||||
<!-- NEXT PARAGRAPH WRAPPED WEIRD INTENTIONALLY SEE #199 -->
|
||||
|
||||
Static variables are similar to constants, which we discussed in the
|
||||
[“Differences Between Variables and Constants”]
|
||||
[differences-between-variables-and-constants]<!-- ignore --> section in Chapter
|
||||
3. The names of static variables are in `SCREAMING_SNAKE_CASE` by convention,
|
||||
and we *must* annotate the variable’s type, which is `&'static str` in this
|
||||
example. Static variables can only store references with the `'static`
|
||||
[differences-between-variables-and-constants]<!-- ignore --> section in
|
||||
Chapter 3. The names of static variables are in `SCREAMING_SNAKE_CASE` by
|
||||
convention, and we *must* annotate the variable’s type, which is `&'static str`
|
||||
in this example. Static variables can only store references with the `'static`
|
||||
lifetime, which means the Rust compiler can figure out the lifetime; we don’t
|
||||
need to annotate it explicitly. Accessing an immutable static variable is safe.
|
||||
|
||||
|
||||
@@ -396,7 +396,7 @@ a reference has a shorter lifetime than what it refers to.
|
||||
|
||||
### Inference of Trait Object Lifetimes
|
||||
|
||||
In Chapter 17 in the [“Using Trait Objects that Allow for Values of Different
|
||||
In Chapter 17 in the [“Using Trait Objects That Allow for Values of Different
|
||||
Types”][using-trait-objects-that-allow-for-values-of-different-types]<!--
|
||||
ignore --> section, we discussed trait objects, consisting of a trait behind a
|
||||
reference, that allow us to use dynamic dispatch. We haven’t yet discussed what
|
||||
|
||||
@@ -626,13 +626,14 @@ In Chapter 10 in the [“Implementing a Trait on a Type”]
|
||||
orphan rule that states we’re allowed to implement a trait on a type as long as
|
||||
either the trait or the type are local to our crate. It’s possible to get
|
||||
around this restriction using the *newtype pattern*, which involves creating a
|
||||
new type in a tuple struct. (We covered tuple structs in the “Using Tuple
|
||||
Structs without Named Fields to Create Different Types” section of Chapter 5.)
|
||||
The tuple struct will have one field and be a thin wrapper around the type we
|
||||
want to implement a trait for. Then the wrapper type is local to our crate, and
|
||||
we can implement the trait on the wrapper. *Newtype* is a term that originates
|
||||
from the Haskell programming language. There is no runtime performance penalty
|
||||
for using this pattern, and the wrapper type is elided at compile time.
|
||||
new type in a tuple struct. (We covered tuple structs in the [“Using Tuple
|
||||
Structs without Named Fields to Create Different Types”][tuple-structs]<!--
|
||||
ignore --> section of Chapter 5.) The tuple struct will have one field and be a
|
||||
thin wrapper around the type we want to implement a trait for. Then the wrapper
|
||||
type is local to our crate, and we can implement the trait on the wrapper.
|
||||
*Newtype* is a term that originates from the Haskell programming language.
|
||||
There is no runtime performance penalty for using this pattern, and the wrapper
|
||||
type is elided at compile time.
|
||||
|
||||
As an example, let’s say we want to implement `Display` on `Vec<T>`, which the
|
||||
orphan rule prevents us from doing directly because the `Display` trait and the
|
||||
@@ -671,12 +672,12 @@ doesn’t have the methods of the value it’s holding. We would have to impleme
|
||||
all the methods of `Vec<T>` directly on `Wrapper` such that the methods
|
||||
delegate to `self.0`, which would allow us to treat `Wrapper` exactly like a
|
||||
`Vec<T>`. If we wanted the new type to have every method the inner type has,
|
||||
implementing the `Deref` trait (discussed in Chapter 15 in the “Treating Smart
|
||||
Pointers like Regular References with the `Deref` Trait” section) on the
|
||||
`Wrapper` to return the inner type would be a solution. If we don’t want the
|
||||
`Wrapper` type to have all the methods of the inner type—for example, to
|
||||
restrict the `Wrapper` type’s behavior—we would have to implement just the
|
||||
methods we do want manually.
|
||||
implementing the `Deref` trait (discussed in Chapter 15 in the [“Treating Smart
|
||||
Pointers Like Regular References with the `Deref`
|
||||
Trait”][smart-pointer-deref]<!-- ignore --> section) on the `Wrapper` to return
|
||||
the inner type would be a solution. If we don’t want the `Wrapper` type to have
|
||||
all the methods of the inner type—for example, to restrict the `Wrapper` type’s
|
||||
behavior—we would have to implement just the methods we do want manually.
|
||||
|
||||
Now you know how the newtype pattern is used in relation to traits; it’s also a
|
||||
useful pattern even when traits are not involved. Let’s switch focus and look
|
||||
@@ -688,3 +689,5 @@ ch10-02-traits.html#implementing-a-trait-on-a-type
|
||||
ch13-02-iterators.html#the-iterator-trait-and-the-next-method
|
||||
[traits-defining-shared-behavior]:
|
||||
ch10-02-traits.html#traits-defining-shared-behavior
|
||||
[smart-pointer-deref]: ch15-02-deref.html#treating-smart-pointers-like-regular-references-with-the-deref-trait
|
||||
[tuple-structs]: ch05-01-defining-structs.html#using-tuple-structs-without-named-fields-to-create-different-types
|
||||
|
||||
@@ -6,8 +6,9 @@ examine why newtypes are useful as types. Then we’ll move on to type aliases,
|
||||
feature similar to newtypes but with slightly different semantics. We’ll also
|
||||
discuss the `!` type and dynamically sized types.
|
||||
|
||||
> Note: The next section assumes you’ve read the earlier section “The Newtype
|
||||
> Pattern to Implement External Traits on External Types.”
|
||||
> Note: The next section assumes you’ve read the earlier section [“Using the
|
||||
> Newtype Pattern to Implement External Traits on External
|
||||
> Types.”][using-the-newtype-pattern]<!-- ignore -->
|
||||
|
||||
### Using the Newtype Pattern for Type Safety and Abstraction
|
||||
|
||||
@@ -306,7 +307,7 @@ types behind a pointer of some kind.
|
||||
We can combine `str` with all kinds of pointers: for example, `Box<str>` or
|
||||
`Rc<str>`. In fact, you’ve seen this before but with a different dynamically
|
||||
sized type: traits. Every trait is a dynamically sized type we can refer to by
|
||||
using the name of the trait. In Chapter 17 in the [“Using Trait Objects that
|
||||
using the name of the trait. In Chapter 17 in the [“Using Trait Objects That
|
||||
Allow for Values of Different Types”]
|
||||
[using-trait-objects-that-allow-for-values-of-different-types]<!-- ignore -->
|
||||
section, we mentioned that to use traits as trait objects, we must put them
|
||||
@@ -360,3 +361,4 @@ ch17-01-what-is-oo.html#encapsulation-that-hides-implementation-details
|
||||
ch06-02-match.html#the-match-control-flow-operator
|
||||
[using-trait-objects-that-allow-for-values-of-different-types]:
|
||||
ch17-02-trait-objects.html#using-trait-objects-that-allow-for-values-of-different-types
|
||||
[using-the-newtype-pattern]: ch19-03-advanced-traits.html#using-the-newtype-pattern-to-implement-external-traits-on-external-types
|
||||
|
||||
@@ -149,10 +149,13 @@ fn returns_closure() -> Box<dyn Fn(i32) -> i32> {
|
||||
```
|
||||
|
||||
This code will compile just fine. For more about trait objects, refer to the
|
||||
“Using Trait Objects That Allow for Values of Different Types” section in
|
||||
Chapter 17.
|
||||
[“Using Trait Objects That Allow for Values of Different Types”]
|
||||
[using-trait-objects-that-allow-for-values-of-different-types]<!-- ignore -->
|
||||
section in Chapter 17.
|
||||
|
||||
Next, let’s look at macros!
|
||||
|
||||
[advanced-traits]:
|
||||
ch19-03-advanced-traits.html#advanced-traits
|
||||
[using-trait-objects-that-allow-for-values-of-different-types]:
|
||||
ch17-02-trait-objects.html#using-trait-objects-that-allow-for-values-of-different-types
|
||||
|
||||
Reference in New Issue
Block a user