mirror of
https://github.com/rust-lang/book.git
synced 2026-11-30 20:04:31 -06:00
Merge pull request #446 from rust-lang/ch7-tr
Ch7 edits after technical review
This commit is contained in:
+187
-144
@@ -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
|
||||
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
|
||||
own. But what happens if find yourself with too many functions? Rust has a
|
||||
module system that handles the problem of wanting to to re-use code while
|
||||
keeping your code organized.
|
||||
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 keeping
|
||||
your code organized.
|
||||
|
||||
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
|
||||
@@ -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:
|
||||
|
||||
* You declare a new module with the keyword `mod`
|
||||
* By default, everything is set as private, but you can use the `pub` keyword
|
||||
to make the module public, and therefore visible outside of the namespace.
|
||||
* By default, everything is set as private (including modules). You can use the
|
||||
`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
|
||||
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
|
||||
that we’ve been using so far our project will be a library:
|
||||
|
||||
```bash
|
||||
```text
|
||||
$ cargo new communicator
|
||||
$ cd communicator
|
||||
```
|
||||
@@ -47,7 +48,7 @@ $ cd communicator
|
||||
Notice that Cargo generated *src/lib.rs* instead of *src/main.rs*. Inside
|
||||
*src/lib.rs* we’ll find this:
|
||||
|
||||
Filename: src/lib.rs
|
||||
<span class="filename">Filename: src/lib.rs</span>
|
||||
|
||||
```rust
|
||||
#[cfg(test)]
|
||||
@@ -58,10 +59,10 @@ mod tests {
|
||||
}
|
||||
```
|
||||
|
||||
Cargo creates an empty test to help us get our library started, rather
|
||||
than the “Hello, world!” binary that we get with the `--bin` option. We’ll look
|
||||
at the `#[]` and `mod tests` syntax a little later, but for now just make sure
|
||||
to leave it in your *src/lib.rs*.
|
||||
Cargo creates an empty test to help us get our library started, rather than the
|
||||
“Hello, world!” binary that we get with the `--bin` option. We’ll look at the
|
||||
`#[]` and `mod tests` syntax a little later, but for now just make sure to
|
||||
leave it in your *src/lib.rs*.
|
||||
|
||||
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
|
||||
@@ -76,9 +77,9 @@ you have for your code.
|
||||
For our `communicator` networking library, we’re first going to define a module
|
||||
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
|
||||
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
|
||||
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.
|
||||
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
|
||||
mod network {
|
||||
@@ -112,23 +114,30 @@ mod client {
|
||||
}
|
||||
```
|
||||
|
||||
<caption>
|
||||
<figcaption>
|
||||
|
||||
Listing 7-1: The `network` module and the `client` module defined side-by-side
|
||||
in *src/lib.rs*
|
||||
</caption>
|
||||
|
||||
</figcaption>
|
||||
</figure>
|
||||
|
||||
Now we have a `network::connect` function and a `client::connect` function.
|
||||
These can have completely different functionality, and the function names do
|
||||
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
|
||||
grow to keep related functionality organized together and separate
|
||||
While in this case, we’re building a library, there's nothing special about
|
||||
*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
|
||||
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
|
||||
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
|
||||
mod network {
|
||||
@@ -142,9 +151,12 @@ mod network {
|
||||
}
|
||||
```
|
||||
|
||||
<caption>
|
||||
<figcaption>
|
||||
|
||||
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`
|
||||
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
|
||||
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
|
||||
organization of our example from Listing 7-1 looks like when thought of this
|
||||
way:
|
||||
@@ -173,7 +185,7 @@ communicator
|
||||
|
||||
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
|
||||
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
|
||||
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
|
||||
@@ -184,9 +196,10 @@ structure you would like.
|
||||
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
|
||||
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
|
||||
mod client {
|
||||
@@ -205,10 +218,13 @@ mod network {
|
||||
}
|
||||
```
|
||||
|
||||
<caption>
|
||||
Listing 7-3: Three modules, `client`, `network`, and `network::server` all
|
||||
<figcaption>
|
||||
|
||||
Listing 7-3: Three modules, `client`, `network`, and `network::server`, all
|
||||
defined in *src/lib.rs*
|
||||
</caption>
|
||||
|
||||
</figcaption>
|
||||
</figure>
|
||||
|
||||
which has this module hierarchy:
|
||||
|
||||
@@ -219,14 +235,17 @@ communicator
|
||||
└── server
|
||||
```
|
||||
|
||||
If these modules had many functions, and each function was getting long, we
|
||||
would have to scroll through this file to find the code we wanted to work with.
|
||||
This would be a good reason to pull each of the `client`, `network`, and
|
||||
`server` modules 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:
|
||||
If these modules had many functions, and those functions were getting long, it
|
||||
would be difficult to scroll through this file to find the code we wanted to
|
||||
work with. Because the functions are nested inside one or more mod blocks, the
|
||||
lines of code inside the functions will start getting long as well. These would
|
||||
be good reasons to pull each of the `client`, `network`, and `server` modules
|
||||
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
|
||||
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
|
||||
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
|
||||
defined inside that module.
|
||||
|
||||
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
|
||||
removed in the previous step:
|
||||
|
||||
File: src/client.rs
|
||||
<span class="filename">Filename: src/client.rs</span>
|
||||
|
||||
```rust
|
||||
fn connect() {
|
||||
@@ -262,7 +279,7 @@ fn connect() {
|
||||
```
|
||||
|
||||
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,
|
||||
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
|
||||
crate rather than a binary crate:
|
||||
|
||||
```bash
|
||||
```text
|
||||
$ cargo build
|
||||
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!
|
||||
|
||||
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:
|
||||
|
||||
Filename: src/lib.rs
|
||||
<span class="filename">Filename: src/lib.rs</span>
|
||||
|
||||
```rust,ignore
|
||||
mod client;
|
||||
@@ -314,9 +331,9 @@ mod client;
|
||||
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
|
||||
fn connect() {
|
||||
@@ -328,8 +345,8 @@ mod server {
|
||||
}
|
||||
```
|
||||
|
||||
Notice that we still have a `mod` declaration within this module file;
|
||||
this is because we still want `server` to be a sub-module of `network`.
|
||||
Notice that we still have a `mod` declaration within this module file; this is
|
||||
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:
|
||||
`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
|
||||
contents:
|
||||
|
||||
Filename: src/network.rs
|
||||
<span class="filename">Filename: src/network.rs</span>
|
||||
|
||||
```rust,ignore
|
||||
fn connect() {
|
||||
@@ -347,19 +364,21 @@ fn connect() {
|
||||
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:
|
||||
|
||||
Filename: src/server.rs
|
||||
<span class="filename">Filename: src/server.rs</span>
|
||||
|
||||
```rust
|
||||
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
|
||||
Compiling communicator v0.1.0 (file:///projects/communicator)
|
||||
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
|
||||
*src/server.rs*
|
||||
</caption>
|
||||
|
||||
</figcaption>
|
||||
</figure>
|
||||
|
||||
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
|
||||
different than `src/lib.rs` somehow; let’s keep reading to understand why.
|
||||
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.
|
||||
|
||||
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:
|
||||
|
||||
> note: maybe move this module `network` to its own directory via
|
||||
`network/mod.rs`
|
||||
```text
|
||||
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
|
||||
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:
|
||||
|
||||
```bash
|
||||
```text
|
||||
$ mkdir src/network
|
||||
$ mv src/network.rs src/network/mod.rs
|
||||
$ 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
|
||||
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
|
||||
*network::server* into *src/server.rs*? The reason is that Rust wouldn’t be
|
||||
able to tell that `server` was supposed to be a submodule of `network` if the
|
||||
*server.rs* file was in the *src* directory. To make it clearer why Rust can’t
|
||||
tell, let’s consider a different example where we have this module hierarchy
|
||||
with all the definitions in *src/lib.rs*:
|
||||
`network::server` module into *src/server.rs*? The reason is that Rust wouldn’t
|
||||
be able to tell that `server` was supposed to be a submodule of `network` if
|
||||
the *server.rs* file was in the *src* directory. To make it clearer why Rust
|
||||
can’t tell, let’s consider a different example with the following module
|
||||
hierarchy, where all the definitions are in *src/lib.rs*:
|
||||
|
||||
```text
|
||||
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:
|
||||
|
||||
* 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
|
||||
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:
|
||||
for `foo` in a file named *foo/mod.rs*.
|
||||
|
||||
```text
|
||||
├── foo
|
||||
│ ├── bar.rs (contains the declarations in `foo::bar`)
|
||||
│ └── mod.rs (contains the declarations in `foo`, including `mod bar`)
|
||||
```
|
||||
These 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:
|
||||
|
||||
* The modules themselves should be declared in their parent module’s file using
|
||||
the `mod` keyword.
|
||||
```text
|
||||
├── 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!
|
||||
|
||||
@@ -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
|
||||
not being used:
|
||||
|
||||
```bash
|
||||
```text
|
||||
warning: function is never used: `connect`, #[warn(dead_code)] on by default
|
||||
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.
|
||||
|
||||
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
|
||||
do that by creating a binary crate in the same directory as our library crate,
|
||||
by making a `src/main.rs` file containing this code:
|
||||
`connect` library as if we were another project, calling it externally. To do
|
||||
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:
|
||||
|
||||
Filename: src/main.rs
|
||||
<span class="filename">Filename: src/main.rs</span>
|
||||
|
||||
```rust,ignore
|
||||
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
|
||||
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
|
||||
`client` module. However, invoking `cargo build` will now give us an error
|
||||
after the warnings:
|
||||
|
||||
```bash
|
||||
```text
|
||||
error: module `client` is private
|
||||
--> 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
|
||||
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
|
||||
that it’s used in our own program and will stop warning that the item is
|
||||
unused.
|
||||
that it’s used in our own program and will stop warning that the item is unused.
|
||||
|
||||
### 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
|
||||
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
|
||||
`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
|
||||
pub mod client;
|
||||
@@ -596,7 +629,7 @@ mod network;
|
||||
|
||||
The `pub` goes right before `mod`. Let’s try building again:
|
||||
|
||||
```bash
|
||||
```text
|
||||
<warnings>
|
||||
error: function `connect` is private
|
||||
--> 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
|
||||
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
|
||||
pub fn connect() {
|
||||
@@ -618,7 +651,7 @@ pub fn connect() {
|
||||
|
||||
And run `cargo build` again:
|
||||
|
||||
```bash
|
||||
```text
|
||||
warning: function is never used: `connect`, #[warn(dead_code)] on by default
|
||||
--> 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
|
||||
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
|
||||
pub fn connect() {
|
||||
@@ -656,7 +689,7 @@ mod server;
|
||||
|
||||
And compile:
|
||||
|
||||
```bash
|
||||
```text
|
||||
warning: function is never used: `connect`, #[warn(dead_code)] on by default
|
||||
--> 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
|
||||
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
|
||||
`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
|
||||
pub mod client;
|
||||
@@ -687,7 +720,7 @@ pub mod network;
|
||||
|
||||
Now if we compile, that warning is gone:
|
||||
|
||||
```bash
|
||||
```text
|
||||
warning: function is never used: `connect`, #[warn(dead_code)] on by default
|
||||
--> 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:
|
||||
|
||||
1. If an item is public, it can be accessed through any of its
|
||||
parent modules.
|
||||
1. If an item is public, it can be accessed through any of its parent modules.
|
||||
2. If an item is private, it may be accessed only by the current module and its
|
||||
child modules.
|
||||
|
||||
### Privacy Examples
|
||||
|
||||
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
|
||||
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`
|
||||
function will have errors. Then try compiling to see if you were right, and read
|
||||
on for discussion of the errors!
|
||||
function will have errors. Then try compiling to see if you were right, and
|
||||
read on for discussion of 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
|
||||
`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.
|
||||
|
||||
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.
|
||||
|
||||
* 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
|
||||
`::outermost::middle_secret_function()`? (The two colons at the beginning
|
||||
mean that we want to refer to the namespaces starting from the root
|
||||
namespace.)
|
||||
`::outermost::middle_secret_function()`? (The two colons at the beginning mean
|
||||
that we want to refer to the modules starting from the root module.)
|
||||
|
||||
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
|
||||
|
||||
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.
|
||||
|
||||
Filename: src/main.rs
|
||||
<figure>
|
||||
<span class="filename">Filename: src/main.rs</span>
|
||||
|
||||
```rust
|
||||
pub mod a {
|
||||
pub mod series {
|
||||
pub mod of {
|
||||
pub fn namespaces() {}
|
||||
pub fn nested_modules() {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
namespaces
|
||||
</caption>
|
||||
|
||||
</figcaption>
|
||||
</figure>
|
||||
|
||||
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.
|
||||
@@ -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
|
||||
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
|
||||
pub mod a {
|
||||
pub mod series {
|
||||
pub mod of {
|
||||
pub fn namespaces() {}
|
||||
pub fn nested_modules() {}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -828,17 +872,17 @@ pub mod a {
|
||||
use a::series::of;
|
||||
|
||||
fn main() {
|
||||
of::namespaces();
|
||||
of::nested_modules();
|
||||
}
|
||||
```
|
||||
|
||||
The line `use a::series::of;` has made it so that anywhere in this scope that
|
||||
we would want to refer to the `of` namespace, instead of having to say
|
||||
`a::series::of`, we can replace that with `of`.
|
||||
The line `use a::series::of;` means that rather than using the full
|
||||
`a::series::of` path wherever we want to refer to the `of` module, we can use
|
||||
`of`.
|
||||
|
||||
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
|
||||
`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
|
||||
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 series {
|
||||
pub mod of {
|
||||
pub fn namespaces() {}
|
||||
pub fn nested_modules() {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
use a::series::of::namespaces;
|
||||
use a::series::of::nested_modules;
|
||||
|
||||
fn main() {
|
||||
namespaces();
|
||||
nested_modules();
|
||||
}
|
||||
```
|
||||
|
||||
This allows us to exclude any of the modules and just reference the function at
|
||||
the callsite.
|
||||
This allows us to exclude all of the modules and reference the function
|
||||
directly.
|
||||
|
||||
Since enums also form this kind of namespace, we can import an enum’s variants
|
||||
with `use` as well. For any kind of `use` statement, if you’re importing
|
||||
multiple items from one namespace, you can list them using curly braces and
|
||||
commas in the last position, like so:
|
||||
Since enums also form a sort of namespace like modules, we can import an enum’s
|
||||
variants with `use` as well. For any kind of `use` statement, if you’re
|
||||
importing multiple items from one namespace, you can list them using curly
|
||||
braces and commas in the last position, like so:
|
||||
|
||||
```rust
|
||||
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
|
||||
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
|
||||
pub mod client;
|
||||
@@ -943,12 +987,11 @@ communicator
|
||||
└── 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
|
||||
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
|
||||
<span class="filename">Filename: src/lib.rs</span>
|
||||
|
||||
```rust
|
||||
#[cfg(test)]
|
||||
@@ -962,7 +1005,7 @@ mod tests {
|
||||
|
||||
Run the tests by invoking the `cargo test` command:
|
||||
|
||||
```bash
|
||||
```text
|
||||
$ cargo test
|
||||
Compiling communicator v0.1.0 (file:///projects/communicator)
|
||||
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
|
||||
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
|
||||
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
|
||||
@@ -1017,7 +1060,7 @@ parent module instead of to the root module.
|
||||
For these reasons, in the `tests` module especially, `use super::something` is
|
||||
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
|
||||
#[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
|
||||
result output will be:
|
||||
|
||||
```bash
|
||||
```text
|
||||
$ cargo test
|
||||
Compiling communicator v0.1.0 (file:///projects/communicator)
|
||||
Running target/debug/communicator-92007ddb5330fa5a
|
||||
|
||||
Binary file not shown.
@@ -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
|
||||
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
|
||||
module system that handles the problem of wanting to re-use code while
|
||||
keeping your code organized.
|
||||
module system that handles the problem of wanting to re-use code while keeping
|
||||
your code organized.
|
||||
|
||||
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
|
||||
@@ -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:
|
||||
|
||||
* You declare a new module with the keyword `mod`
|
||||
* By default, everything is set as private, but you can use the `pub` keyword
|
||||
to make the module public, and therefore visible outside of the namespace.
|
||||
* By default, everything is set as private (including modules). You can use the
|
||||
`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
|
||||
modules, into scope so that it’s easier to refer to them.
|
||||
|
||||
|
||||
@@ -31,10 +31,10 @@ mod tests {
|
||||
}
|
||||
```
|
||||
|
||||
Cargo creates an empty test to help us get our library started, rather
|
||||
than the “Hello, world!” binary that we get with the `--bin` option. We’ll look
|
||||
at the `#[]` and `mod tests` syntax a little later, but for now just make sure
|
||||
to leave it in your *src/lib.rs*.
|
||||
Cargo creates an empty test to help us get our library started, rather than the
|
||||
“Hello, world!” binary that we get with the `--bin` option. We’ll look at the
|
||||
`#[]` and `mod tests` syntax a little later, but for now just make sure to
|
||||
leave it in your *src/lib.rs*.
|
||||
|
||||
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
|
||||
@@ -49,7 +49,7 @@ you have for your code.
|
||||
For our `communicator` networking library, we’re first going to define a module
|
||||
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
|
||||
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>
|
||||
|
||||
@@ -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.
|
||||
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>
|
||||
<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.
|
||||
|
||||
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,
|
||||
we can also put modules inside of modules. This can be useful as your modules
|
||||
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
|
||||
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
|
||||
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>
|
||||
<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
|
||||
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
|
||||
*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>
|
||||
<span class="filename">Filename: src/lib.rs</span>
|
||||
@@ -191,7 +192,7 @@ mod network {
|
||||
|
||||
<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*
|
||||
|
||||
</figcaption>
|
||||
@@ -206,12 +207,15 @@ communicator
|
||||
└── server
|
||||
```
|
||||
|
||||
If these modules had many functions, and each function was getting long, we
|
||||
would have to scroll through this file to find the code we wanted to work with.
|
||||
This would be a good reason to pull each of the `client`, `network`, and
|
||||
`server` modules 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:
|
||||
If these modules had many functions, and those functions were getting long, it
|
||||
would be difficult to scroll through this file to find the code we wanted to
|
||||
work with. Because the functions are nested inside one or more mod blocks, the
|
||||
lines of code inside the functions will start getting long as well. These would
|
||||
be good reasons to pull each of the `client`, `network`, and `server` modules
|
||||
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>
|
||||
|
||||
@@ -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
|
||||
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
|
||||
@@ -315,8 +317,8 @@ mod server {
|
||||
}
|
||||
```
|
||||
|
||||
Notice that we still have a `mod` declaration within this module file;
|
||||
this is because we still want `server` to be a sub-module of `network`.
|
||||
Notice that we still have a `mod` declaration within this module file; this is
|
||||
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:
|
||||
`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>
|
||||
|
||||
@@ -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
|
||||
out something we haven’t yet talked about doing:
|
||||
|
||||
> note: maybe move this module `network` to its own directory via
|
||||
`network/mod.rs`
|
||||
```text
|
||||
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
|
||||
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
|
||||
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
|
||||
`network::server` into *src/server.rs*? The reason is that Rust wouldn’t be
|
||||
able to tell that `server` was supposed to be a submodule of `network` if the
|
||||
*server.rs* file was in the *src* directory. To make it clearer why Rust can’t
|
||||
tell, let’s consider a different example where we have this module hierarchy
|
||||
with all the definitions in *src/lib.rs*:
|
||||
`network::server` module into *src/server.rs*? The reason is that Rust wouldn’t
|
||||
be able to tell that `server` was supposed to be a submodule of `network` if
|
||||
the *server.rs* file was in the *src* directory. To make it clearer why Rust
|
||||
can’t tell, let’s consider a different example with the following module
|
||||
hierarchy, where all the definitions are in *src/lib.rs*:
|
||||
|
||||
```text
|
||||
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*.
|
||||
* If a module named `foo` does have submodules, you should put the declarations
|
||||
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
|
||||
├── foo
|
||||
│ ├── bar.rs (contains the declarations in `foo::bar`)
|
||||
│ └── mod.rs (contains the declarations in `foo`, including `mod bar`)
|
||||
```
|
||||
These 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:
|
||||
|
||||
* The modules themselves should be declared in their parent module’s file using
|
||||
the `mod` keyword.
|
||||
```text
|
||||
├── 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!
|
||||
|
||||
@@ -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.
|
||||
|
||||
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
|
||||
do that by creating a binary crate in the same directory as our library crate,
|
||||
`connect` library as if we were another project, calling it externally. To do
|
||||
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:
|
||||
|
||||
<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
|
||||
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
|
||||
`client` module. However, invoking `cargo build` will now give us an error
|
||||
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
|
||||
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
|
||||
that it’s used in our own program and will stop warning that the item is
|
||||
unused.
|
||||
that it’s used in our own program and will stop warning that the item is unused.
|
||||
|
||||
### 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
|
||||
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>
|
||||
|
||||
@@ -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
|
||||
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
|
||||
`src/lib.rs` to make `network` public too:
|
||||
*src/lib.rs* to make `network` public too:
|
||||
|
||||
<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:
|
||||
|
||||
1. If an item is public, it can be accessed through any of its
|
||||
parent modules.
|
||||
1. If an item is public, it can be accessed through any of its parent modules.
|
||||
2. If an item is private, it may be accessed only by the current module and its
|
||||
child modules.
|
||||
|
||||
@@ -251,8 +259,8 @@ incorrect
|
||||
</figure>
|
||||
|
||||
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
|
||||
on for discussion of the errors!
|
||||
function will have errors. Then try compiling to see if you were right, and
|
||||
read on for discussion of the errors!
|
||||
|
||||
#### Looking at the Errors
|
||||
|
||||
@@ -286,9 +294,8 @@ understand why.
|
||||
* What if the `inside` module was public?
|
||||
* What if `outermost` was public and `inside` was private?
|
||||
* What if, in the body of `inner_function`, you called
|
||||
`::outermost::middle_secret_function()`? (The two colons at the beginning
|
||||
mean that we want to refer to the namespaces starting from the root
|
||||
namespace.)
|
||||
`::outermost::middle_secret_function()`? (The two colons at the beginning mean
|
||||
that we want to refer to the modules starting from the root module.)
|
||||
|
||||
Feel free to design more experiments and try them out!
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
## Importing Names
|
||||
|
||||
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.
|
||||
|
||||
<figure>
|
||||
@@ -11,13 +11,13 @@ here in Listing 7-6.
|
||||
pub mod a {
|
||||
pub mod series {
|
||||
pub mod of {
|
||||
pub fn namespaces() {}
|
||||
pub fn nested_modules() {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
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>
|
||||
|
||||
@@ -44,7 +44,7 @@ bringing the `a::series::of` namespace into a binary crate’s root scope:
|
||||
pub mod a {
|
||||
pub mod series {
|
||||
pub mod of {
|
||||
pub fn namespaces() {}
|
||||
pub fn nested_modules() {}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -52,17 +52,17 @@ pub mod a {
|
||||
use a::series::of;
|
||||
|
||||
fn main() {
|
||||
of::namespaces();
|
||||
of::nested_modules();
|
||||
}
|
||||
```
|
||||
|
||||
The line `use a::series::of;` has made it so that anywhere in this scope that
|
||||
we would want to refer to the `of` namespace, instead of having to say
|
||||
`a::series::of`, we can replace that with `of`.
|
||||
The line `use a::series::of;` means that rather than using the full
|
||||
`a::series::of` path wherever we want to refer to the `of` module, we can use
|
||||
`of`.
|
||||
|
||||
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
|
||||
`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
|
||||
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 series {
|
||||
pub mod of {
|
||||
pub fn namespaces() {}
|
||||
pub fn nested_modules() {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
use a::series::of::namespaces;
|
||||
use a::series::of::nested_modules;
|
||||
|
||||
fn main() {
|
||||
namespaces();
|
||||
nested_modules();
|
||||
}
|
||||
```
|
||||
|
||||
This allows us to exclude any of the modules and just reference the function at
|
||||
the callsite.
|
||||
This allows us to exclude all of the modules and reference the function
|
||||
directly.
|
||||
|
||||
Since enums also form this kind of namespace, we can import an enum’s variants
|
||||
with `use` as well. For any kind of `use` statement, if you’re importing
|
||||
multiple items from one namespace, you can list them using curly braces and
|
||||
commas in the last position, like so:
|
||||
Since enums also form a sort of namespace like modules, we can import an enum’s
|
||||
variants with `use` as well. For any kind of `use` statement, if you’re
|
||||
importing multiple items from one namespace, you can list them using curly
|
||||
braces and commas in the last position, like so:
|
||||
|
||||
```rust
|
||||
enum TrafficLight {
|
||||
@@ -167,9 +167,9 @@ communicator
|
||||
└── 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 our
|
||||
`client::connect` function from this `it_works` function, even though we’re not
|
||||
going to be checking any functionality right now:
|
||||
|
||||
<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
|
||||
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
|
||||
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
|
||||
|
||||
Reference in New Issue
Block a user