Merge pull request #446 from rust-lang/ch7-tr

Ch7 edits after technical review
This commit is contained in:
Carol (Nichols || Goulding)
2017-02-18 22:35:38 -05:00
committed by GitHub
6 changed files with 280 additions and 225 deletions
+187 -144
View File
@@ -7,9 +7,9 @@ When you start writing programs in Rust, your code might live solely in the
`main` function. As your code grows, you’ll eventually move functionality out `main` function. As your code grows, you’ll eventually move functionality out
into other functions, both for re-use and for better organization. By splitting into other functions, both for re-use and for better organization. By splitting
your code up into smaller chunks, each chunk is easier to understand on its your code up into smaller chunks, each chunk is easier to understand on its
own. But what happens if find yourself with too many functions? Rust has a own. But what happens if you find yourself with too many functions? Rust has a
module system that handles the problem of wanting to to re-use code while module system that handles the problem of wanting to re-use code while keeping
keeping your code organized. your code organized.
In the same way that you extract lines of code into a function, you can extract In the same way that you extract lines of code into a function, you can extract
functions (and other code like structs and enums too) into different modules. A functions (and other code like structs and enums too) into different modules. A
@@ -18,8 +18,9 @@ you can choose whether those definitions are visible outside their module
(public) or not (private). Here’s an overview of how modules work: (public) or not (private). Here’s an overview of how modules work:
* You declare a new module with the keyword `mod` * You declare a new module with the keyword `mod`
* By default, everything is set as private, but you can use the `pub` keyword * By default, everything is set as private (including modules). You can use the
to make the module public, and therefore visible outside of the namespace. `pub` keyword to make a module public and therefore visible outside of its
namespace.
* The `use` keyword allows you to bring modules, or the definitions inside * The `use` keyword allows you to bring modules, or the definitions inside
modules, into scope so that it’s easier to refer to them. modules, into scope so that it’s easier to refer to them.
@@ -39,7 +40,7 @@ call our library `communicator`. By default, cargo will create a library unless
another type of project is specified, so if we leave off the `--bin` option another type of project is specified, so if we leave off the `--bin` option
that we’ve been using so far our project will be a library: that we’ve been using so far our project will be a library:
```bash ```text
$ cargo new communicator $ cargo new communicator
$ cd communicator $ cd communicator
``` ```
@@ -47,7 +48,7 @@ $ cd communicator
Notice that Cargo generated *src/lib.rs* instead of *src/main.rs*. Inside Notice that Cargo generated *src/lib.rs* instead of *src/main.rs*. Inside
*src/lib.rs* we’ll find this: *src/lib.rs* we’ll find this:
Filename: src/lib.rs <span class="filename">Filename: src/lib.rs</span>
```rust ```rust
#[cfg(test)] #[cfg(test)]
@@ -58,10 +59,10 @@ mod tests {
} }
``` ```
Cargo creates an empty test to help us get our library started, rather Cargo creates an empty test to help us get our library started, rather than the
than the “Hello, world!” binary that we get with the `--bin` option. We’ll look “Hello, world!” binary that we get with the `--bin` option. We’ll look at the
at the `#[]` and `mod tests` syntax a little later, but for now just make sure `#[]` and `mod tests` syntax a little later, but for now just make sure to
to leave it in your *src/lib.rs*. leave it in your *src/lib.rs*.
Since we don’t have a *src/main.rs*, there’s nothing for Cargo to execute with Since we don’t have a *src/main.rs*, there’s nothing for Cargo to execute with
the `cargo run` command. Therefore, we will be using the `cargo build` command the `cargo run` command. Therefore, we will be using the `cargo build` command
@@ -76,9 +77,9 @@ you have for your code.
For our `communicator` networking library, we’re first going to define a module For our `communicator` networking library, we’re first going to define a module
named `network` that contains the definition of a function called `connect`. named `network` that contains the definition of a function called `connect`.
Every module definition in Rust starts with the `mod` keyword. Add this code to Every module definition in Rust starts with the `mod` keyword. Add this code to
the beginning of the *lib.rs* file, above the test code: the beginning of the *src/lib.rs* file, above the test code:
Filename: src/lib.rs <span class="filename">Filename: src/lib.rs</span>
```rust ```rust
mod network { mod network {
@@ -96,9 +97,10 @@ specify the module and use the namespace syntax `::`, like so:
We can also have multiple modules, side-by-side, in the same *src/lib.rs* file. We can also have multiple modules, side-by-side, in the same *src/lib.rs* file.
For example, to have a `client` module too, that also has a function named For example, to have a `client` module too, that also has a function named
`connect`, we can add: `connect`, we can add it as shown in Listing 7-1:
Filename: src/lib.rs <figure>
<span class="filename">Filename: src/lib.rs</span>
```rust ```rust
mod network { mod network {
@@ -112,23 +114,30 @@ mod client {
} }
``` ```
<caption> <figcaption>
Listing 7-1: The `network` module and the `client` module defined side-by-side Listing 7-1: The `network` module and the `client` module defined side-by-side
in *src/lib.rs* in *src/lib.rs*
</caption>
</figcaption>
</figure>
Now we have a `network::connect` function and a `client::connect` function. Now we have a `network::connect` function and a `client::connect` function.
These can have completely different functionality, and the function names do These can have completely different functionality, and the function names do
not conflict with each other since they’re in different modules. not conflict with each other since they’re in different modules.
We can also put modules inside of modules. This can be useful as your modules While in this case, we’re building a library, there's nothing special about
grow to keep related functionality organized together and separate *src/lib.rs*. We could also make use of submodules in *src/main.rs* as well. In
fact, we can also put modules inside of modules. This can be useful as your
modules grow to keep related functionality organized together and separate
functionality apart. The choice of how you organize your code depends on how functionality apart. The choice of how you organize your code depends on how
you think about the relationship between the parts of your code. For instance, you think about the relationship between the parts of your code. For instance,
the `client` code and its `connect` function might make more sense to users of the `client` code and its `connect` function might make more sense to users of
our library if it was inside the `network` namespace instead, like so: our library if it was inside the `network` namespace instead, like in Listing
7-2:
Filename: src/lib.rs <figure>
<span class="filename">Filename: src/lib.rs</span>
```rust ```rust
mod network { mod network {
@@ -142,9 +151,12 @@ mod network {
} }
``` ```
<caption> <figcaption>
Listing 7-2: Moving the `client` module inside of the `network` module Listing 7-2: Moving the `client` module inside of the `network` module
</caption>
</figcaption>
</figure>
In your *src/lib.rs* file, replace the existing `mod network` and `mod client` In your *src/lib.rs* file, replace the existing `mod network` and `mod client`
definitions with this one that has the `client` module as an inner module of definitions with this one that has the `client` module as an inner module of
@@ -152,7 +164,7 @@ definitions with this one that has the `client` module as an inner module of
`network::client::connect`: again, the two functions named `connect` don’t `network::client::connect`: again, the two functions named `connect` don’t
conflict with each other since they’re in different namespaces. conflict with each other since they’re in different namespaces.
In this way, modules form a hierarchy. The contents of `src/lib.rs` are at the In this way, modules form a hierarchy. The contents of *src/lib.rs* are at the
topmost level, and the submodules are at lower levels. Here’s what the topmost level, and the submodules are at lower levels. Here’s what the
organization of our example from Listing 7-1 looks like when thought of this organization of our example from Listing 7-1 looks like when thought of this
way: way:
@@ -173,7 +185,7 @@ communicator
You can see that in Listing 7-2, `client` is a child of the `network` module, You can see that in Listing 7-2, `client` is a child of the `network` module,
rather than a sibling. More complicated projects can have a lot of modules, and rather than a sibling. More complicated projects can have a lot of modules, and
they’ll need to be orgnaized logically in order to keep track of them. What they’ll need to be organized logically in order to keep track of them. What
“logically” means in your project is up to you and depends on how you and users “logically” means in your project is up to you and depends on how you and users
of your library think about your project’s domain. Use the techniques we’ve of your library think about your project’s domain. Use the techniques we’ve
shown here to create side-by-side modules and nested modules in whatever shown here to create side-by-side modules and nested modules in whatever
@@ -184,9 +196,10 @@ structure you would like.
Modules form a hierarchical structure, much like another structure in computing Modules form a hierarchical structure, much like another structure in computing
that you’re used to: file systems! We can use Rust’s module system along with that you’re used to: file systems! We can use Rust’s module system along with
multiple files to split Rust projects up so that not everything lives in multiple files to split Rust projects up so that not everything lives in
*src/lib.rs*. For this example, we will start with this code in *src/lib.rs*: *src/lib.rs*. For this example, we will start with the code in Listing 7-3:
File: src/lib.rs <figure>
<span class="filename">Filename: src/lib.rs</span>
```rust ```rust
mod client { mod client {
@@ -205,10 +218,13 @@ mod network {
} }
``` ```
<caption> <figcaption>
Listing 7-3: Three modules, `client`, `network`, and `network::server` all
Listing 7-3: Three modules, `client`, `network`, and `network::server`, all
defined in *src/lib.rs* defined in *src/lib.rs*
</caption>
</figcaption>
</figure>
which has this module hierarchy: which has this module hierarchy:
@@ -219,14 +235,17 @@ communicator
└── server └── server
``` ```
If these modules had many functions, and each function was getting long, we If these modules had many functions, and those functions were getting long, it
would have to scroll through this file to find the code we wanted to work with. would be difficult to scroll through this file to find the code we wanted to
This would be a good reason to pull each of the `client`, `network`, and work with. Because the functions are nested inside one or more mod blocks, the
`server` modules out of *src/lib.rs* and into their own files. Let’s start by lines of code inside the functions will start getting long as well. These would
extracting the `client` module into another file. First, replace the `client` be good reasons to pull each of the `client`, `network`, and `server` modules
module code in *src/lib.rs* with the following: out of *src/lib.rs* and into their own files.
File: src/lib.rs Let’s start by extracting the `client` module into another file. First, replace
the `client` module code in *src/lib.rs* with the following:
<span class="filename">Filename: src/lib.rs</span>
```rust,ignore ```rust,ignore
mod client; mod client;
@@ -242,19 +261,17 @@ mod network {
} }
``` ```
<!-- I will add wingdings/ghosting in libreoffice /Carol -->
We’re still *defining* the `client` module here, but by removing the curly We’re still *defining* the `client` module here, but by removing the curly
braces and definitions inside the `client` module and replacing them with a braces and definitions inside the `client` module and replacing them with a
semicolon, we’re letting Rust know to look in another location for the code semicolon, we’re letting Rust know to look in another location for the code
defined inside that module. defined inside that module.
So now we need to create the external file with that module name. Create a So now we need to create the external file with that module name. Create a
`client.rs` file in your *src/* directory, then open it up and enter the *client.rs* file in your *src/* directory, then open it up and enter the
following, which is the `connect` function in the `client` module that we following, which is the `connect` function in the `client` module that we
removed in the previous step: removed in the previous step:
File: src/client.rs <span class="filename">Filename: src/client.rs</span>
```rust ```rust
fn connect() { fn connect() {
@@ -262,7 +279,7 @@ fn connect() {
``` ```
Note that we don’t need a `mod` declaration in this file; that’s because we Note that we don’t need a `mod` declaration in this file; that’s because we
already declared the `client` module with `mod` in `src/lib.rs`. This file just already declared the `client` module with `mod` in *src/lib.rs*. This file just
provides the *contents* of the `client` module. If we put a `mod client` here, provides the *contents* of the `client` module. If we put a `mod client` here,
we’d be giving the `client` module its own submodule named `client`! we’d be giving the `client` module its own submodule named `client`!
@@ -275,7 +292,7 @@ Now, everything should compile successfully, though you’ll get a few warnings.
Remember to use `cargo build` instead of `cargo run` since we have a library Remember to use `cargo build` instead of `cargo run` since we have a library
crate rather than a binary crate: crate rather than a binary crate:
```bash ```text
$ cargo build $ cargo build
Compiling communicator v0.1.0 (file:///projects/communicator) Compiling communicator v0.1.0 (file:///projects/communicator)
@@ -303,10 +320,10 @@ about those warnings for now; we’ll address them later in the chapter. The goo
news is that they’re just warnings; our project was built successfully! news is that they’re just warnings; our project was built successfully!
Let’s extract the `network` module into its own file next, using the same Let’s extract the `network` module into its own file next, using the same
pattern. In `src/lib.rs`, delete the body of the `network` module and add a pattern. In *src/lib.rs*, delete the body of the `network` module and add a
semicolon to the declaration, like so: semicolon to the declaration, like so:
Filename: src/lib.rs <span class="filename">Filename: src/lib.rs</span>
```rust,ignore ```rust,ignore
mod client; mod client;
@@ -314,9 +331,9 @@ mod client;
mod network; mod network;
``` ```
Then create a new `src/network.rs` file and enter the following: Then create a new *src/network.rs* file and enter the following:
Filename: src/network.rs <span class="filename">Filename: src/network.rs</span>
```rust ```rust
fn connect() { fn connect() {
@@ -328,8 +345,8 @@ mod server {
} }
``` ```
Notice that we still have a `mod` declaration within this module file; Notice that we still have a `mod` declaration within this module file; this is
this is because we still want `server` to be a sub-module of `network`. because we still want `server` to be a sub-module of `network`.
Now run `cargo build` again. Success! We have one more module to extract: Now run `cargo build` again. Success! We have one more module to extract:
`server`. Because it’s a sub-module—that is, a module within a module—our `server`. Because it’s a sub-module—that is, a module within a module—our
@@ -338,7 +355,7 @@ work. We’re going to try anyway so that we can see the error. First change
*src/network.rs* to have `mod server;` instead of the `server` module’s *src/network.rs* to have `mod server;` instead of the `server` module’s
contents: contents:
Filename: src/network.rs <span class="filename">Filename: src/network.rs</span>
```rust,ignore ```rust,ignore
fn connect() { fn connect() {
@@ -347,19 +364,21 @@ fn connect() {
mod server; mod server;
``` ```
Then create a `src/server.rs` file and enter the contents of the `server` Then create a *src/server.rs* file and enter the contents of the `server`
module that we extracted: module that we extracted:
Filename: src/server.rs <span class="filename">Filename: src/server.rs</span>
```rust ```rust
fn connect() { fn connect() {
} }
``` ```
When we try to `cargo build`, we’ll get this error: When we try to `cargo build`, we’ll get the error shown in Listing 7-4:
```bash <figure>
```text
$ cargo build $ cargo build
Compiling communicator v0.1.0 (file:///projects/communicator) Compiling communicator v0.1.0 (file:///projects/communicator)
error: cannot declare a new module at this location error: cannot declare a new module at this location
@@ -380,20 +399,24 @@ note: ... or maybe `use` the module `server` instead of possibly redeclaring it
| ^^^^^^ | ^^^^^^
``` ```
<caption> <figcaption>
Listing 7-4: Error when trying to extract the `server` submodule into Listing 7-4: Error when trying to extract the `server` submodule into
*src/server.rs* *src/server.rs*
</caption>
</figcaption>
</figure>
The error says we `cannot declare a new module at this location` and is The error says we `cannot declare a new module at this location` and is
pointing to the `mod server;` line in `src/network.rs`. So `src/network.rs` is pointing to the `mod server;` line in *src/network.rs*. So *src/network.rs* is
different than `src/lib.rs` somehow; let’s keep reading to understand why. different than *src/lib.rs* somehow; let’s keep reading to understand why.
The note in the middle of Listing 7-4 is actually pretty helpful, as it points The note in the middle of Listing 7-4 is actually pretty helpful, as it points
out something we haven’t yet talked about doing: out something we haven’t yet talked about doing:
> note: maybe move this module `network` to its own directory via ```text
`network/mod.rs` note: maybe move this module `network` to its own directory via `network/mod.rs`
```
Instead of continuing to follow the same file naming pattern we used Instead of continuing to follow the same file naming pattern we used
previously, we can do what the note suggests: previously, we can do what the note suggests:
@@ -405,7 +428,7 @@ previously, we can do what the note suggests:
Here are commands to carry out these steps: Here are commands to carry out these steps:
```bash ```text
$ mkdir src/network $ mkdir src/network
$ mv src/network.rs src/network/mod.rs $ mv src/network.rs src/network/mod.rs
$ mv src/server.rs src/network $ mv src/server.rs src/network
@@ -435,13 +458,13 @@ The corresponding file layout now looks like this:
So when we wanted to extract the `network::server` module, why did we have to So when we wanted to extract the `network::server` module, why did we have to
also change the *src/network.rs* file into the *src/network/mod.rs* file, and also change the *src/network.rs* file into the *src/network/mod.rs* file, and
also put the code for `network::server` in the `network` directory in put the code for `network::server` in the *network* directory in
*src/network/server.rs*, instead of just being able to extract the *src/network/server.rs*, instead of just being able to extract the
*network::server* into *src/server.rs*? The reason is that Rust wouldn’t be `network::server` module into *src/server.rs*? The reason is that Rust wouldn’t
able to tell that `server` was supposed to be a submodule of `network` if the be able to tell that `server` was supposed to be a submodule of `network` if
*server.rs* file was in the *src* directory. To make it clearer why Rust can’t the *server.rs* file was in the *src* directory. To make it clearer why Rust
tell, let’s consider a different example where we have this module hierarchy can’t tell, let’s consider a different example with the following module
with all the definitions in *src/lib.rs*: hierarchy, where all the definitions are in *src/lib.rs*:
```text ```text
communicator communicator
@@ -473,21 +496,22 @@ top-level *src/client.rs* is unambiguously the code that belongs to the
In summary, these are the rules of modules with regards to files: In summary, these are the rules of modules with regards to files:
* If a module named `foo` has no submodules, you should put the declarations * If a module named `foo` has no submodules, you should put the declarations
for `foo` in a file named `foo.rs`. for `foo` in a file named *foo.rs*.
* If a module named `foo` does have submodules, you should put the declarations * If a module named `foo` does have submodules, you should put the declarations
for `foo` in a file named `foo/mod.rs`. for `foo` in a file named *foo/mod.rs*.
* The first two rules apply recursively, so that if a module named `foo` has a
submodule named `bar` and `bar` does not have submodules, you should have the
following files in your `src` directory:
```text These rules apply recursively, so that if a module named `foo` has a submodule
├── foo named `bar` and `bar` does not have submodules, you should have the following
│   ├── bar.rs (contains the declarations in `foo::bar`) files in your *src* directory:
│   └── mod.rs (contains the declarations in `foo`, including `mod bar`)
```
* The modules themselves should be declared in their parent module’s file using ```text
the `mod` keyword. ├── foo
│   ├── bar.rs (contains the declarations in `foo::bar`)
│   └── mod.rs (contains the declarations in `foo`, including `mod bar`)
```
The modules themselves should be declared in their parent module’s file using
the `mod` keyword.
Next, we’ll talk about the `pub` keyword, and get rid of those warnings! Next, we’ll talk about the `pub` keyword, and get rid of those warnings!
@@ -500,7 +524,7 @@ able to build our project, but we still get some warning messages about the
`client::connect`, `network::connect`, and `network::server::connect` functions `client::connect`, `network::connect`, and `network::server::connect` functions
not being used: not being used:
```bash ```text
warning: function is never used: `connect`, #[warn(dead_code)] on by default warning: function is never used: `connect`, #[warn(dead_code)] on by default
src/client.rs:1:1 src/client.rs:1:1
| |
@@ -527,11 +551,11 @@ functions go unused. The point of creating them is that they will be used by
another project and not our own. another project and not our own.
To understand why this program invokes these warnings, let’s try using the To understand why this program invokes these warnings, let’s try using the
`connect` library as if we were another project, calling it externally. We can `connect` library as if we were another project, calling it externally. To do
do that by creating a binary crate in the same directory as our library crate, that, we’ll create a binary crate in the same directory as our library crate,
by making a `src/main.rs` file containing this code: by making a *src/main.rs* file containing this code:
Filename: src/main.rs <span class="filename">Filename: src/main.rs</span>
```rust,ignore ```rust,ignore
extern crate communicator; extern crate communicator;
@@ -549,11 +573,21 @@ quite common for executable projects: most functionality is in a library crate,
and the binary crate uses that library crate. This way, other programs can also and the binary crate uses that library crate. This way, other programs can also
use the library crate, and it’s a nice separation of concerns. use the library crate, and it’s a nice separation of concerns.
From the point of view of a crate outside of the `communicator` library looking
in, all of the modules we've been creating are within a module that has the
same name as the crate, `communicator`. We call the top-level module of a crate
the *root module*.
Also note that even if we're using an external crate within a submodule of our
project, the `extern crate` should go in our root module (so in *src/main.rs*
or *src/lib.rs*). Then, in our submodules, we can refer to items from external
crates as if the items are top-level modules.
Our binary crate right now just calls our library’s `connect` function from the Our binary crate right now just calls our library’s `connect` function from the
`client` module. However, invoking `cargo build` will now give us an error `client` module. However, invoking `cargo build` will now give us an error
after the warnings: after the warnings:
```bash ```text
error: module `client` is private error: module `client` is private
--> src/main.rs:4:5 --> src/main.rs:4:5
| |
@@ -575,8 +609,7 @@ the function is unused will go away. Marking something public lets Rust know
that we intend for the function to be used by code outside of our program. Rust that we intend for the function to be used by code outside of our program. Rust
considers the theoretical external usage that’s now possible as the function considers the theoretical external usage that’s now possible as the function
“being used.” Thus, when something is marked as public, Rust will not require “being used.” Thus, when something is marked as public, Rust will not require
that it’s used in our own program and will stop warning that the item is that it’s used in our own program and will stop warning that the item is unused.
unused.
### Making a Function Public ### Making a Function Public
@@ -584,9 +617,9 @@ To tell Rust to make something public, we add the `pub` keyword to the start of
the declaration of the item we want to make public. We’ll focus on fixing the the declaration of the item we want to make public. We’ll focus on fixing the
warning that tells us that `client::connect` has gone unused for now, as well warning that tells us that `client::connect` has gone unused for now, as well
as the “module `client` is private” error from our binary crate. Modify as the “module `client` is private” error from our binary crate. Modify
`src/lib.rs` to make the `client` module public, like so: *src/lib.rs* to make the `client` module public, like so:
Filename: src/lib.rs <span class="filename">Filename: src/lib.rs</span>
```rust,ignore ```rust,ignore
pub mod client; pub mod client;
@@ -596,7 +629,7 @@ mod network;
The `pub` goes right before `mod`. Let’s try building again: The `pub` goes right before `mod`. Let’s try building again:
```bash ```text
<warnings> <warnings>
error: function `connect` is private error: function `connect` is private
--> src/main.rs:4:5 --> src/main.rs:4:5
@@ -607,9 +640,9 @@ error: function `connect` is private
Hooray! We have a different error! Yes, different error messages are a cause Hooray! We have a different error! Yes, different error messages are a cause
for celebration. The new error says “function `connect` is private”, so let’s for celebration. The new error says “function `connect` is private”, so let’s
edit `src/client.rs` to make `client::connect` public too: edit *src/client.rs* to make `client::connect` public too:
Filename: src/client.rs <span class="filename">Filename: src/client.rs</span>
```rust ```rust
pub fn connect() { pub fn connect() {
@@ -618,7 +651,7 @@ pub fn connect() {
And run `cargo build` again: And run `cargo build` again:
```bash ```text
warning: function is never used: `connect`, #[warn(dead_code)] on by default warning: function is never used: `connect`, #[warn(dead_code)] on by default
--> src/network/mod.rs:1:1 --> src/network/mod.rs:1:1
| |
@@ -643,9 +676,9 @@ called.
In our case though, we *do* want the other two functions to be part of our In our case though, we *do* want the other two functions to be part of our
crate’s public API, so let’s mark them as `pub` as well to try to get rid of crate’s public API, so let’s mark them as `pub` as well to try to get rid of
the remaining warnings. Modify `src/network/mod.rs` to be: the remaining warnings. Modify *src/network/mod.rs* to be:
Filename: src/network/mod.rs <span class="filename">Filename: src/network/mod.rs</span>
```rust,ignore ```rust,ignore
pub fn connect() { pub fn connect() {
@@ -656,7 +689,7 @@ mod server;
And compile: And compile:
```bash ```text
warning: function is never used: `connect`, #[warn(dead_code)] on by default warning: function is never used: `connect`, #[warn(dead_code)] on by default
--> src/network/mod.rs:1:1 --> src/network/mod.rs:1:1
| |
@@ -675,9 +708,9 @@ Hmmm, we’re still getting an unused function warning even though
within the module, but the `network` module that the function resides in is not within the module, but the `network` module that the function resides in is not
public. We’re working from the interior of the library out this time, where public. We’re working from the interior of the library out this time, where
with `client::connect` we worked from the outside in. We need to change with `client::connect` we worked from the outside in. We need to change
`src/lib.rs` to make `network` public too: *src/lib.rs* to make `network` public too:
Filename: src/lib.rs <span class="filename">Filename: src/lib.rs</span>
```rust,ignore ```rust,ignore
pub mod client; pub mod client;
@@ -687,7 +720,7 @@ pub mod network;
Now if we compile, that warning is gone: Now if we compile, that warning is gone:
```bash ```text
warning: function is never used: `connect`, #[warn(dead_code)] on by default warning: function is never used: `connect`, #[warn(dead_code)] on by default
--> src/network/server.rs:1:1 --> src/network/server.rs:1:1
| |
@@ -701,17 +734,17 @@ Only one warning left! Try to fix this one on your own!
Overall, these are the rules for item visibility: Overall, these are the rules for item visibility:
1. If an item is public, it can be accessed through any of its 1. If an item is public, it can be accessed through any of its parent modules.
parent modules.
2. If an item is private, it may be accessed only by the current module and its 2. If an item is private, it may be accessed only by the current module and its
child modules. child modules.
### Privacy Examples ### Privacy Examples
Let’s look at a few more examples to get some practice. Create a new library Let’s look at a few more examples to get some practice. Create a new library
project and enter the code in Listing 7-5 into your new project’s `src/lib.rs`: project and enter the code in Listing 7-5 into your new project’s *src/lib.rs*:
Filename: src/lib.rs <figure>
<span class="filename">Filename: src/lib.rs</span>
```rust,ignore ```rust,ignore
mod outermost { mod outermost {
@@ -734,9 +767,17 @@ fn try_me() {
} }
``` ```
<figcaption>
Listing 7-5: Examples of private and public functions, some of which are
incorrect
</figcaption>
</figure>
Before you try to compile this code, make a guess about which lines in `try_me` Before you try to compile this code, make a guess about which lines in `try_me`
function will have errors. Then try compiling to see if you were right, and read function will have errors. Then try compiling to see if you were right, and
on for discussion of the errors! read on for discussion of the errors!
#### Looking at the Errors #### Looking at the Errors
@@ -747,7 +788,7 @@ is allowed to access the `outermost` module since `outermost` is in the current
The call to `outermost::middle_function` will work. This is because The call to `outermost::middle_function` will work. This is because
`middle_function` is public, and `try_me` is accessing `middle_function` `middle_function` is public, and `try_me` is accessing `middle_function`
through its parent module, `outermost` We determined in the previous paragraph through its parent module, `outermost`. We determined in the previous paragraph
that this module is accessible. that this module is accessible.
The call to `outermost::middle_secret_function` will cause a compilation error. The call to `outermost::middle_secret_function` will cause a compilation error.
@@ -768,11 +809,10 @@ errors, then compile to see if you’re right and use the privacy rules to
understand why. understand why.
* What if the `inside` module was public? * What if the `inside` module was public?
* What if `outside` was public and `inside` was private? * What if `outermost` was public and `inside` was private?
* What if, in the body of `inner_function`, you called * What if, in the body of `inner_function`, you called
`::outermost::middle_secret_function()`? (The two colons at the beginning `::outermost::middle_secret_function()`? (The two colons at the beginning mean
mean that we want to refer to the namespaces starting from the root that we want to refer to the modules starting from the root module.)
namespace.)
Feel free to design more experiments and try them out! Feel free to design more experiments and try them out!
@@ -781,29 +821,33 @@ Next, let’s talk about bringing items into a scope with the `use` keyword.
## Importing Names ## Importing Names
We’ve covered how to call functions defined within a module using the module We’ve covered how to call functions defined within a module using the module
name as part of the call, as in the call to the `namespaces` function shown name as part of the call, as in the call to the `nested_modules` function shown
here in Listing 7-6. here in Listing 7-6.
Filename: src/main.rs <figure>
<span class="filename">Filename: src/main.rs</span>
```rust ```rust
pub mod a { pub mod a {
pub mod series { pub mod series {
pub mod of { pub mod of {
pub fn namespaces() {} pub fn nested_modules() {}
} }
} }
} }
fn main() { fn main() {
a::series::of::namespaces(); a::series::of::nested_modules();
} }
``` ```
<caption> <figcaption>
Listing 7-6: Calling a function by fully specifying its enclosing module’s Listing 7-6: Calling a function by fully specifying its enclosing module’s
namespaces namespaces
</caption>
</figcaption>
</figure>
As you can see, referring to the fully qualified name can get quite lengthy. As you can see, referring to the fully qualified name can get quite lengthy.
Luckily, Rust has a keyword to make these calls more concise. Luckily, Rust has a keyword to make these calls more concise.
@@ -812,15 +856,15 @@ Luckily, Rust has a keyword to make these calls more concise.
Rust’s `use` keyword works to shorten lengthy function calls by bringing the Rust’s `use` keyword works to shorten lengthy function calls by bringing the
modules of the function you want to call into a scope. Here’s an example of modules of the function you want to call into a scope. Here’s an example of
bringing the `a::series::of` namespace into a binary crate’s root scope: bringing the `a::series::of` module into a binary crate’s root scope:
Filename: src/main.rs <span class="filename">Filename: src/main.rs</span>
```rust ```rust
pub mod a { pub mod a {
pub mod series { pub mod series {
pub mod of { pub mod of {
pub fn namespaces() {} pub fn nested_modules() {}
} }
} }
} }
@@ -828,17 +872,17 @@ pub mod a {
use a::series::of; use a::series::of;
fn main() { fn main() {
of::namespaces(); of::nested_modules();
} }
``` ```
The line `use a::series::of;` has made it so that anywhere in this scope that The line `use a::series::of;` means that rather than using the full
we would want to refer to the `of` namespace, instead of having to say `a::series::of` path wherever we want to refer to the `of` module, we can use
`a::series::of`, we can replace that with `of`. `of`.
The `use` keyword brings only what we have specified into scope; it does not The `use` keyword brings only what we have specified into scope; it does not
bring children of modules into scope. That’s why we still have to say bring children of modules into scope. That’s why we still have to say
`of::namespaces` when we want to call the `namespaces` function. `of::nested_modules` when we want to call the `nested_modules` function.
We could have chosen to bring the function itself into scope, by instead We could have chosen to bring the function itself into scope, by instead
specifying the function in the `use` as follows: specifying the function in the `use` as follows:
@@ -847,25 +891,25 @@ specifying the function in the `use` as follows:
pub mod a { pub mod a {
pub mod series { pub mod series {
pub mod of { pub mod of {
pub fn namespaces() {} pub fn nested_modules() {}
} }
} }
} }
use a::series::of::namespaces; use a::series::of::nested_modules;
fn main() { fn main() {
namespaces(); nested_modules();
} }
``` ```
This allows us to exclude any of the modules and just reference the function at This allows us to exclude all of the modules and reference the function
the callsite. directly.
Since enums also form this kind of namespace, we can import an enum’s variants Since enums also form a sort of namespace like modules, we can import an enum’s
with `use` as well. For any kind of `use` statement, if you’re importing variants with `use` as well. For any kind of `use` statement, if you’re
multiple items from one namespace, you can list them using curly braces and importing multiple items from one namespace, you can list them using curly
commas in the last position, like so: braces and commas in the last position, like so:
```rust ```rust
enum TrafficLight { enum TrafficLight {
@@ -912,9 +956,9 @@ might also pull in more things than you expected and cause naming conflicts.
As you now know, when you create a library crate, Cargo makes a `tests` module As you now know, when you create a library crate, Cargo makes a `tests` module
for you. Let’s go into more detail about that now. In your `communicator` for you. Let’s go into more detail about that now. In your `communicator`
project, open `src/lib.rs`. project, open *src/lib.rs*.
Filename: src/lib.rs <span class="filename">Filename: src/lib.rs</span>
```rust,ignore ```rust,ignore
pub mod client; pub mod client;
@@ -943,12 +987,11 @@ communicator
└── tests └── tests
``` ```
Tests are for exercising the code within our library, so let’s try to call our
`client::connect` function from this `it_works` function, even though we’re not
going to be checking any functionality right now:
Tests are for exercising the code within our library, so let’s try to call <span class="filename">Filename: src/lib.rs</span>
our `client::connect` function from this `it_works` function, even though
we’re not going to be checking any functionality right now:
Filename: src/lib.rs
```rust ```rust
#[cfg(test)] #[cfg(test)]
@@ -962,7 +1005,7 @@ mod tests {
Run the tests by invoking the `cargo test` command: Run the tests by invoking the `cargo test` command:
```bash ```text
$ cargo test $ cargo test
Compiling communicator v0.1.0 (file:///projects/communicator) Compiling communicator v0.1.0 (file:///projects/communicator)
error[E0433]: failed to resolve. Use of undeclared type or module `client` error[E0433]: failed to resolve. Use of undeclared type or module `client`
@@ -979,7 +1022,7 @@ warning: function is never used: `connect`, #[warn(dead_code)] on by default
``` ```
The compilation failed, but why? We don’t need to place `communicator::` in The compilation failed, but why? We don’t need to place `communicator::` in
front of the function like we did in `src/main.rs` because we are definitely front of the function like we did in *src/main.rs* because we are definitely
within the `communicator` library crate here. The reason is that paths are within the `communicator` library crate here. The reason is that paths are
always relative to the current module, which here is `tests`. The only always relative to the current module, which here is `tests`. The only
exception is in a `use` statement, where paths are relative to the crate root exception is in a `use` statement, where paths are relative to the crate root
@@ -1017,7 +1060,7 @@ parent module instead of to the root module.
For these reasons, in the `tests` module especially, `use super::something` is For these reasons, in the `tests` module especially, `use super::something` is
usually the way to go. So now our test looks like this: usually the way to go. So now our test looks like this:
Filename: src/lib.rs <span class="filename">Filename: src/lib.rs</span>
```rust ```rust
#[cfg(test)] #[cfg(test)]
@@ -1034,7 +1077,7 @@ mod tests {
If we run `cargo test` again, the test will pass and the first part of the test If we run `cargo test` again, the test will pass and the first part of the test
result output will be: result output will be:
```bash ```text
$ cargo test $ cargo test
Compiling communicator v0.1.0 (file:///projects/communicator) Compiling communicator v0.1.0 (file:///projects/communicator)
Running target/debug/communicator-92007ddb5330fa5a Running target/debug/communicator-92007ddb5330fa5a
Binary file not shown.
+5 -4
View File
@@ -5,8 +5,8 @@ When you start writing programs in Rust, your code might live solely in the
into other functions, both for re-use and for better organization. By splitting into other functions, both for re-use and for better organization. By splitting
your code up into smaller chunks, each chunk is easier to understand on its your code up into smaller chunks, each chunk is easier to understand on its
own. But what happens if you find yourself with too many functions? Rust has a own. But what happens if you find yourself with too many functions? Rust has a
module system that handles the problem of wanting to re-use code while module system that handles the problem of wanting to re-use code while keeping
keeping your code organized. your code organized.
In the same way that you extract lines of code into a function, you can extract In the same way that you extract lines of code into a function, you can extract
functions (and other code like structs and enums too) into different modules. A functions (and other code like structs and enums too) into different modules. A
@@ -15,8 +15,9 @@ you can choose whether those definitions are visible outside their module
(public) or not (private). Here’s an overview of how modules work: (public) or not (private). Here’s an overview of how modules work:
* You declare a new module with the keyword `mod` * You declare a new module with the keyword `mod`
* By default, everything is set as private, but you can use the `pub` keyword * By default, everything is set as private (including modules). You can use the
to make the module public, and therefore visible outside of the namespace. `pub` keyword to make a module public and therefore visible outside of its
namespace.
* The `use` keyword allows you to bring modules, or the definitions inside * The `use` keyword allows you to bring modules, or the definitions inside
modules, into scope so that it’s easier to refer to them. modules, into scope so that it’s easier to refer to them.
+45 -41
View File
@@ -31,10 +31,10 @@ mod tests {
} }
``` ```
Cargo creates an empty test to help us get our library started, rather Cargo creates an empty test to help us get our library started, rather than the
than the “Hello, world!” binary that we get with the `--bin` option. We’ll look “Hello, world!” binary that we get with the `--bin` option. We’ll look at the
at the `#[]` and `mod tests` syntax a little later, but for now just make sure `#[]` and `mod tests` syntax a little later, but for now just make sure to
to leave it in your *src/lib.rs*. leave it in your *src/lib.rs*.
Since we don’t have a *src/main.rs*, there’s nothing for Cargo to execute with Since we don’t have a *src/main.rs*, there’s nothing for Cargo to execute with
the `cargo run` command. Therefore, we will be using the `cargo build` command the `cargo run` command. Therefore, we will be using the `cargo build` command
@@ -49,7 +49,7 @@ you have for your code.
For our `communicator` networking library, we’re first going to define a module For our `communicator` networking library, we’re first going to define a module
named `network` that contains the definition of a function called `connect`. named `network` that contains the definition of a function called `connect`.
Every module definition in Rust starts with the `mod` keyword. Add this code to Every module definition in Rust starts with the `mod` keyword. Add this code to
the beginning of the *lib.rs* file, above the test code: the beginning of the *src/lib.rs* file, above the test code:
<span class="filename">Filename: src/lib.rs</span> <span class="filename">Filename: src/lib.rs</span>
@@ -69,7 +69,7 @@ specify the module and use the namespace syntax `::`, like so:
We can also have multiple modules, side-by-side, in the same *src/lib.rs* file. We can also have multiple modules, side-by-side, in the same *src/lib.rs* file.
For example, to have a `client` module too, that also has a function named For example, to have a `client` module too, that also has a function named
`connect`, we can add: `connect`, we can add it as shown in Listing 7-1:
<figure> <figure>
<span class="filename">Filename: src/lib.rs</span> <span class="filename">Filename: src/lib.rs</span>
@@ -99,13 +99,14 @@ These can have completely different functionality, and the function names do
not conflict with each other since they’re in different modules. not conflict with each other since they’re in different modules.
While in this case, we’re building a library, there's nothing special about While in this case, we’re building a library, there's nothing special about
*lib.rs*. We could also make use of submodules in a *main.rs* as well. In fact, *src/lib.rs*. We could also make use of submodules in *src/main.rs* as well. In
we can also put modules inside of modules. This can be useful as your modules fact, we can also put modules inside of modules. This can be useful as your
grow to keep related functionality organized together and separate modules grow to keep related functionality organized together and separate
functionality apart. The choice of how you organize your code depends on how functionality apart. The choice of how you organize your code depends on how
you think about the relationship between the parts of your code. For instance, you think about the relationship between the parts of your code. For instance,
the `client` code and its `connect` function might make more sense to users of the `client` code and its `connect` function might make more sense to users of
our library if it was inside the `network` namespace instead, like so: our library if it was inside the `network` namespace instead, like in Listing
7-2:
<figure> <figure>
<span class="filename">Filename: src/lib.rs</span> <span class="filename">Filename: src/lib.rs</span>
@@ -167,7 +168,7 @@ structure you would like.
Modules form a hierarchical structure, much like another structure in computing Modules form a hierarchical structure, much like another structure in computing
that you’re used to: file systems! We can use Rust’s module system along with that you’re used to: file systems! We can use Rust’s module system along with
multiple files to split Rust projects up so that not everything lives in multiple files to split Rust projects up so that not everything lives in
*src/lib.rs*. For this example, we will start with this code in *src/lib.rs*: *src/lib.rs*. For this example, we will start with the code in Listing 7-3:
<figure> <figure>
<span class="filename">Filename: src/lib.rs</span> <span class="filename">Filename: src/lib.rs</span>
@@ -191,7 +192,7 @@ mod network {
<figcaption> <figcaption>
Listing 7-3: Three modules, `client`, `network`, and `network::server` all Listing 7-3: Three modules, `client`, `network`, and `network::server`, all
defined in *src/lib.rs* defined in *src/lib.rs*
</figcaption> </figcaption>
@@ -206,12 +207,15 @@ communicator
└── server └── server
``` ```
If these modules had many functions, and each function was getting long, we If these modules had many functions, and those functions were getting long, it
would have to scroll through this file to find the code we wanted to work with. would be difficult to scroll through this file to find the code we wanted to
This would be a good reason to pull each of the `client`, `network`, and work with. Because the functions are nested inside one or more mod blocks, the
`server` modules out of *src/lib.rs* and into their own files. Let’s start by lines of code inside the functions will start getting long as well. These would
extracting the `client` module into another file. First, replace the `client` be good reasons to pull each of the `client`, `network`, and `server` modules
module code in *src/lib.rs* with the following: out of *src/lib.rs* and into their own files.
Let’s start by extracting the `client` module into another file. First, replace
the `client` module code in *src/lib.rs* with the following:
<span class="filename">Filename: src/lib.rs</span> <span class="filename">Filename: src/lib.rs</span>
@@ -229,8 +233,6 @@ mod network {
} }
``` ```
<!-- I will add wingdings/ghosting in libreoffice /Carol -->
We’re still *defining* the `client` module here, but by removing the curly We’re still *defining* the `client` module here, but by removing the curly
braces and definitions inside the `client` module and replacing them with a braces and definitions inside the `client` module and replacing them with a
semicolon, we’re letting Rust know to look in another location for the code semicolon, we’re letting Rust know to look in another location for the code
@@ -315,8 +317,8 @@ mod server {
} }
``` ```
Notice that we still have a `mod` declaration within this module file; Notice that we still have a `mod` declaration within this module file; this is
this is because we still want `server` to be a sub-module of `network`. because we still want `server` to be a sub-module of `network`.
Now run `cargo build` again. Success! We have one more module to extract: Now run `cargo build` again. Success! We have one more module to extract:
`server`. Because it’s a sub-module—that is, a module within a module—our `server`. Because it’s a sub-module—that is, a module within a module—our
@@ -344,7 +346,7 @@ fn connect() {
} }
``` ```
When we try to `cargo build`, we’ll get this error: When we try to `cargo build`, we’ll get the error shown in Listing 7-4:
<figure> <figure>
@@ -384,8 +386,9 @@ different than *src/lib.rs* somehow; let’s keep reading to understand why.
The note in the middle of Listing 7-4 is actually pretty helpful, as it points The note in the middle of Listing 7-4 is actually pretty helpful, as it points
out something we haven’t yet talked about doing: out something we haven’t yet talked about doing:
> note: maybe move this module `network` to its own directory via ```text
`network/mod.rs` note: maybe move this module `network` to its own directory via `network/mod.rs`
```
Instead of continuing to follow the same file naming pattern we used Instead of continuing to follow the same file naming pattern we used
previously, we can do what the note suggests: previously, we can do what the note suggests:
@@ -427,13 +430,13 @@ The corresponding file layout now looks like this:
So when we wanted to extract the `network::server` module, why did we have to So when we wanted to extract the `network::server` module, why did we have to
also change the *src/network.rs* file into the *src/network/mod.rs* file, and also change the *src/network.rs* file into the *src/network/mod.rs* file, and
also put the code for `network::server` in the `network` directory in put the code for `network::server` in the *network* directory in
*src/network/server.rs*, instead of just being able to extract the *src/network/server.rs*, instead of just being able to extract the
`network::server` into *src/server.rs*? The reason is that Rust wouldn’t be `network::server` module into *src/server.rs*? The reason is that Rust wouldn’t
able to tell that `server` was supposed to be a submodule of `network` if the be able to tell that `server` was supposed to be a submodule of `network` if
*server.rs* file was in the *src* directory. To make it clearer why Rust can’t the *server.rs* file was in the *src* directory. To make it clearer why Rust
tell, let’s consider a different example where we have this module hierarchy can’t tell, let’s consider a different example with the following module
with all the definitions in *src/lib.rs*: hierarchy, where all the definitions are in *src/lib.rs*:
```text ```text
communicator communicator
@@ -468,17 +471,18 @@ In summary, these are the rules of modules with regards to files:
for `foo` in a file named *foo.rs*. for `foo` in a file named *foo.rs*.
* If a module named `foo` does have submodules, you should put the declarations * If a module named `foo` does have submodules, you should put the declarations
for `foo` in a file named *foo/mod.rs*. for `foo` in a file named *foo/mod.rs*.
* The first two rules apply recursively, so that if a module named `foo` has a
submodule named `bar` and `bar` does not have submodules, you should have the
following files in your *src* directory:
```text These rules apply recursively, so that if a module named `foo` has a submodule
├── foo named `bar` and `bar` does not have submodules, you should have the following
│   ├── bar.rs (contains the declarations in `foo::bar`) files in your *src* directory:
│   └── mod.rs (contains the declarations in `foo`, including `mod bar`)
```
* The modules themselves should be declared in their parent module’s file using ```text
the `mod` keyword. ├── foo
│   ├── bar.rs (contains the declarations in `foo::bar`)
│   └── mod.rs (contains the declarations in `foo`, including `mod bar`)
```
The modules themselves should be declared in their parent module’s file using
the `mod` keyword.
Next, we’ll talk about the `pub` keyword, and get rid of those warnings! Next, we’ll talk about the `pub` keyword, and get rid of those warnings!
+20 -13
View File
@@ -34,8 +34,8 @@ functions go unused. The point of creating them is that they will be used by
another project and not our own. another project and not our own.
To understand why this program invokes these warnings, let’s try using the To understand why this program invokes these warnings, let’s try using the
`connect` library as if we were another project, calling it externally. We can `connect` library as if we were another project, calling it externally. To do
do that by creating a binary crate in the same directory as our library crate, that, we’ll create a binary crate in the same directory as our library crate,
by making a *src/main.rs* file containing this code: by making a *src/main.rs* file containing this code:
<span class="filename">Filename: src/main.rs</span> <span class="filename">Filename: src/main.rs</span>
@@ -56,6 +56,16 @@ quite common for executable projects: most functionality is in a library crate,
and the binary crate uses that library crate. This way, other programs can also and the binary crate uses that library crate. This way, other programs can also
use the library crate, and it’s a nice separation of concerns. use the library crate, and it’s a nice separation of concerns.
From the point of view of a crate outside of the `communicator` library looking
in, all of the modules we've been creating are within a module that has the
same name as the crate, `communicator`. We call the top-level module of a crate
the *root module*.
Also note that even if we're using an external crate within a submodule of our
project, the `extern crate` should go in our root module (so in *src/main.rs*
or *src/lib.rs*). Then, in our submodules, we can refer to items from external
crates as if the items are top-level modules.
Our binary crate right now just calls our library’s `connect` function from the Our binary crate right now just calls our library’s `connect` function from the
`client` module. However, invoking `cargo build` will now give us an error `client` module. However, invoking `cargo build` will now give us an error
after the warnings: after the warnings:
@@ -82,8 +92,7 @@ the function is unused will go away. Marking something public lets Rust know
that we intend for the function to be used by code outside of our program. Rust that we intend for the function to be used by code outside of our program. Rust
considers the theoretical external usage that’s now possible as the function considers the theoretical external usage that’s now possible as the function
“being used.” Thus, when something is marked as public, Rust will not require “being used.” Thus, when something is marked as public, Rust will not require
that it’s used in our own program and will stop warning that the item is that it’s used in our own program and will stop warning that the item is unused.
unused.
### Making a Function Public ### Making a Function Public
@@ -114,7 +123,7 @@ error: function `connect` is private
Hooray! We have a different error! Yes, different error messages are a cause Hooray! We have a different error! Yes, different error messages are a cause
for celebration. The new error says “function `connect` is private”, so let’s for celebration. The new error says “function `connect` is private”, so let’s
edit `src/client.rs` to make `client::connect` public too: edit *src/client.rs* to make `client::connect` public too:
<span class="filename">Filename: src/client.rs</span> <span class="filename">Filename: src/client.rs</span>
@@ -182,7 +191,7 @@ Hmmm, we’re still getting an unused function warning even though
within the module, but the `network` module that the function resides in is not within the module, but the `network` module that the function resides in is not
public. We’re working from the interior of the library out this time, where public. We’re working from the interior of the library out this time, where
with `client::connect` we worked from the outside in. We need to change with `client::connect` we worked from the outside in. We need to change
`src/lib.rs` to make `network` public too: *src/lib.rs* to make `network` public too:
<span class="filename">Filename: src/lib.rs</span> <span class="filename">Filename: src/lib.rs</span>
@@ -208,8 +217,7 @@ Only one warning left! Try to fix this one on your own!
Overall, these are the rules for item visibility: Overall, these are the rules for item visibility:
1. If an item is public, it can be accessed through any of its 1. If an item is public, it can be accessed through any of its parent modules.
parent modules.
2. If an item is private, it may be accessed only by the current module and its 2. If an item is private, it may be accessed only by the current module and its
child modules. child modules.
@@ -251,8 +259,8 @@ incorrect
</figure> </figure>
Before you try to compile this code, make a guess about which lines in `try_me` Before you try to compile this code, make a guess about which lines in `try_me`
function will have errors. Then try compiling to see if you were right, and read function will have errors. Then try compiling to see if you were right, and
on for discussion of the errors! read on for discussion of the errors!
#### Looking at the Errors #### Looking at the Errors
@@ -286,9 +294,8 @@ understand why.
* What if the `inside` module was public? * What if the `inside` module was public?
* What if `outermost` was public and `inside` was private? * What if `outermost` was public and `inside` was private?
* What if, in the body of `inner_function`, you called * What if, in the body of `inner_function`, you called
`::outermost::middle_secret_function()`? (The two colons at the beginning `::outermost::middle_secret_function()`? (The two colons at the beginning mean
mean that we want to refer to the namespaces starting from the root that we want to refer to the modules starting from the root module.)
namespace.)
Feel free to design more experiments and try them out! Feel free to design more experiments and try them out!
+23 -23
View File
@@ -1,7 +1,7 @@
## Importing Names ## Importing Names
We’ve covered how to call functions defined within a module using the module We’ve covered how to call functions defined within a module using the module
name as part of the call, as in the call to the `namespaces` function shown name as part of the call, as in the call to the `nested_modules` function shown
here in Listing 7-6. here in Listing 7-6.
<figure> <figure>
@@ -11,13 +11,13 @@ here in Listing 7-6.
pub mod a { pub mod a {
pub mod series { pub mod series {
pub mod of { pub mod of {
pub fn namespaces() {} pub fn nested_modules() {}
} }
} }
} }
fn main() { fn main() {
a::series::of::namespaces(); a::series::of::nested_modules();
} }
``` ```
@@ -36,7 +36,7 @@ Luckily, Rust has a keyword to make these calls more concise.
Rust’s `use` keyword works to shorten lengthy function calls by bringing the Rust’s `use` keyword works to shorten lengthy function calls by bringing the
modules of the function you want to call into a scope. Here’s an example of modules of the function you want to call into a scope. Here’s an example of
bringing the `a::series::of` namespace into a binary crate’s root scope: bringing the `a::series::of` module into a binary crate’s root scope:
<span class="filename">Filename: src/main.rs</span> <span class="filename">Filename: src/main.rs</span>
@@ -44,7 +44,7 @@ bringing the `a::series::of` namespace into a binary crate’s root scope:
pub mod a { pub mod a {
pub mod series { pub mod series {
pub mod of { pub mod of {
pub fn namespaces() {} pub fn nested_modules() {}
} }
} }
} }
@@ -52,17 +52,17 @@ pub mod a {
use a::series::of; use a::series::of;
fn main() { fn main() {
of::namespaces(); of::nested_modules();
} }
``` ```
The line `use a::series::of;` has made it so that anywhere in this scope that The line `use a::series::of;` means that rather than using the full
we would want to refer to the `of` namespace, instead of having to say `a::series::of` path wherever we want to refer to the `of` module, we can use
`a::series::of`, we can replace that with `of`. `of`.
The `use` keyword brings only what we have specified into scope; it does not The `use` keyword brings only what we have specified into scope; it does not
bring children of modules into scope. That’s why we still have to say bring children of modules into scope. That’s why we still have to say
`of::namespaces` when we want to call the `namespaces` function. `of::nested_modules` when we want to call the `nested_modules` function.
We could have chosen to bring the function itself into scope, by instead We could have chosen to bring the function itself into scope, by instead
specifying the function in the `use` as follows: specifying the function in the `use` as follows:
@@ -71,25 +71,25 @@ specifying the function in the `use` as follows:
pub mod a { pub mod a {
pub mod series { pub mod series {
pub mod of { pub mod of {
pub fn namespaces() {} pub fn nested_modules() {}
} }
} }
} }
use a::series::of::namespaces; use a::series::of::nested_modules;
fn main() { fn main() {
namespaces(); nested_modules();
} }
``` ```
This allows us to exclude any of the modules and just reference the function at This allows us to exclude all of the modules and reference the function
the callsite. directly.
Since enums also form this kind of namespace, we can import an enum’s variants Since enums also form a sort of namespace like modules, we can import an enum’s
with `use` as well. For any kind of `use` statement, if you’re importing variants with `use` as well. For any kind of `use` statement, if you’re
multiple items from one namespace, you can list them using curly braces and importing multiple items from one namespace, you can list them using curly
commas in the last position, like so: braces and commas in the last position, like so:
```rust ```rust
enum TrafficLight { enum TrafficLight {
@@ -167,9 +167,9 @@ communicator
└── tests └── tests
``` ```
Tests are for exercising the code within our library, so let’s try to call Tests are for exercising the code within our library, so let’s try to call our
our `client::connect` function from this `it_works` function, even though `client::connect` function from this `it_works` function, even though we’re not
we’re not going to be checking any functionality right now: going to be checking any functionality right now:
<span class="filename">Filename: src/lib.rs</span> <span class="filename">Filename: src/lib.rs</span>
@@ -202,7 +202,7 @@ warning: function is never used: `connect`, #[warn(dead_code)] on by default
``` ```
The compilation failed, but why? We don’t need to place `communicator::` in The compilation failed, but why? We don’t need to place `communicator::` in
front of the function like we did in `src/main.rs` because we are definitely front of the function like we did in *src/main.rs* because we are definitely
within the `communicator` library crate here. The reason is that paths are within the `communicator` library crate here. The reason is that paths are
always relative to the current module, which here is `tests`. The only always relative to the current module, which here is `tests`. The only
exception is in a `use` statement, where paths are relative to the crate root exception is in a `use` statement, where paths are relative to the crate root