Navigation Menu

Skip to content

Commit

Permalink
document advance extern crate/use syntax
Browse files Browse the repository at this point in the history
I took a stab at fixing #28064. Not sure if this all-features-in-one-example approach is the right one. Also I completely made up the terms "star globbing" and "brace expansion globbing" -- they are just called "glob-like syntax" in the reference.
  • Loading branch information
durka committed Sep 5, 2015
1 parent 779b2a9 commit 2cebf36
Showing 1 changed file with 48 additions and 0 deletions.
48 changes: 48 additions & 0 deletions src/doc/trpl/crates-and-modules.md
Expand Up @@ -532,3 +532,51 @@ Goodbye in English: Goodbye.
Hello in Japanese: こんにちは
Goodbye in Japanese: さようなら
```
## Complex imports
Rust offers several advanced options that can add compactness and
convenience to your `extern crate` and `use` statements. Here is an example:
```rust,ignore
extern crate phrases as sayings;
use sayings::japanese::greetings as ja_greetings;
use sayings::japanese::farewells::*;
use sayings::english::{self, greetings as en_greetings, farewells as en_farewells};
fn main() {
println!("Hello in English; {}", en_greetings::hello());
println!("And in Japanese: {}", ja_greetings::hello());
println!("Goodbye in English: {}", english::farewells::goodbye());
println!("Again: {}", en_farewells::goodbye());
println!("And in Japanese: {}", goodbye());
}
```
What's going on here?
First, both `extern crate` and `use` allow renaming the thing that is being
imported. So the crate is still called "phrases", but here we will refer
to it as "sayings". Similarly, the first `use` statement pulls in the
`japanese::farewells` module from the crate, but makes it available as
`jp_farewells` as opposed to simply `farewells`. This can help to avoid
ambiguity when importing similarly-named items from different places.
The second `use` statement uses a star glob to bring in _all_ symbols from the
`sayings::japanese::farewells` module. As you can see we can later refer to
the Japanese `goodbye` function with no module qualifiers. This kind of glob
should be used sparingly.
The third `use` statement bears more explanation. It's using "brace expansion"
globbing to compress three `use` statements into one (this sort of syntax
may be familiar if you've written Linux shell scripts before). The
uncompressed form of this statement would be:
```rust,ignore
use sayings::english;
use sayings::english::greetings as en_greetings;
use sayings::english::farewells as en_farewells;
```
As you can see, the curly brackets compress `use` statements for several items
under the same path, and in this context `self` just refers back to that path.
Note: The curly brackets cannot be nested or mixed with star globbing.

0 comments on commit 2cebf36

Please sign in to comment.