2023-11-29 10:39:24 -05:00
|
|
|
---
|
|
|
|
minutes: 10
|
|
|
|
---
|
|
|
|
|
|
|
|
# use, super, self
|
|
|
|
|
2023-12-31 00:15:07 +01:00
|
|
|
A module can bring symbols from another module into scope with `use`. You will
|
|
|
|
typically see something like this at the top of each module:
|
2023-11-29 10:39:24 -05:00
|
|
|
|
|
|
|
```rust,editable
|
|
|
|
use std::collections::HashSet;
|
|
|
|
use std::process::abort;
|
|
|
|
```
|
|
|
|
|
|
|
|
## Paths
|
2022-12-21 16:36:30 +01:00
|
|
|
|
|
|
|
Paths are resolved as follows:
|
|
|
|
|
|
|
|
1. As a relative path:
|
2023-12-31 00:15:07 +01:00
|
|
|
- `foo` or `self::foo` refers to `foo` in the current module,
|
|
|
|
- `super::foo` refers to `foo` in the parent module.
|
2022-12-21 16:36:30 +01:00
|
|
|
|
|
|
|
2. As an absolute path:
|
2023-12-31 00:15:07 +01:00
|
|
|
- `crate::foo` refers to `foo` in the root of the current crate,
|
|
|
|
- `bar::foo` refers to `foo` in the `bar` crate.
|
2023-04-24 14:51:23 -04:00
|
|
|
|
2023-11-29 10:39:24 -05:00
|
|
|
<details>
|
2023-04-24 14:51:23 -04:00
|
|
|
|
2023-12-31 00:15:07 +01:00
|
|
|
- It is common to "re-export" symbols at a shorter path. For example, the
|
2023-11-29 10:39:24 -05:00
|
|
|
top-level `lib.rs` in a crate might have
|
|
|
|
|
|
|
|
```rust,ignore
|
|
|
|
mod storage;
|
|
|
|
|
|
|
|
pub use storage::disk::DiskStorage;
|
|
|
|
pub use storage::network::NetworkStorage;
|
|
|
|
```
|
|
|
|
|
|
|
|
making `DiskStorage` and `NetworkStorage` available to other crates with a
|
|
|
|
convenient, short path.
|
|
|
|
|
2023-12-31 00:15:07 +01:00
|
|
|
- For the most part, only items that appear in a module need to be `use`'d.
|
|
|
|
However, a trait must be in scope to call any methods on that trait, even if a
|
|
|
|
type implementing that trait is already in scope. For example, to use the
|
2023-11-29 10:39:24 -05:00
|
|
|
`read_to_string` method on a type implementing the `Read` trait, you need to
|
|
|
|
`use std::io::Read`.
|
|
|
|
|
2023-12-31 00:15:07 +01:00
|
|
|
- The `use` statement can have a wildcard: `use std::io::*`. This is discouraged
|
|
|
|
because it is not clear which items are imported, and those might change over
|
|
|
|
time.
|
2023-11-29 10:39:24 -05:00
|
|
|
|
|
|
|
</details>
|