Skip to content

Commit c4aa4da

Browse files
committed
Update use chapter with more detail.
This attempts to update the `use` chapter to explain the kinds of paths and syntax it supports in more detail. This is not an exhaustive explanation of resolution, and there are several things it does not cover.
1 parent e4d826d commit c4aa4da

File tree

2 files changed

+261
-59
lines changed

2 files changed

+261
-59
lines changed

src/items/use-declarations.md

+261-57
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ A _use declaration_ creates one or more local name bindings synonymous with
1313
some other [path]. Usually a `use` declaration is used to shorten the path
1414
required to refer to a module item. These declarations may appear in [modules]
1515
and [blocks], usually at the top.
16+
A `use` declaration is also sometimes called an "import".
1617

1718
[path]: ../paths.md
1819
[modules]: modules.md
@@ -21,7 +22,7 @@ and [blocks], usually at the top.
2122
Use declarations support a number of convenient shortcuts:
2223

2324
* Simultaneously binding a list of paths with a common prefix, using the
24-
glob-like brace syntax `use a::b::{c, d, e::f, g::h::i};`
25+
brace syntax `use a::b::{c, d, e::f, g::h::i};`
2526
* Simultaneously binding a list of paths with a common prefix and their common
2627
parent module, using the `self` keyword, such as `use a::b::{self, c, d::e};`
2728
* Rebinding the target name as a new local name, using the syntax `use p::q::r
@@ -85,75 +86,186 @@ In this example, the module `quux` re-exports two public names defined in
8586

8687
## `use` Paths
8788

88-
> **Note**: This section is incomplete.
89+
The [paths] that are allowed in a `use` item follow the [_SimplePath_] grammar and are similar to the paths that may be used in an expression.
90+
They may create bindings for:
8991

90-
Some examples of what will and will not work for `use` items:
91-
<!-- Note: This example works as-is in either 2015 or 2018. -->
92+
* Nameable [items]
93+
* [Enum variants]
94+
* [Built-in types]
95+
* [Attributes]
96+
* [Derive macros]
9297

93-
```rust
94-
# #![allow(unused_imports)]
95-
use std::path::{self, Path, PathBuf}; // good: std is a crate name
96-
use crate::foo::baz::foobaz; // good: foo is at the root of the crate
98+
They cannot import [associated items], [generic parameters], [local variables], paths with [`Self`], or [tool attributes]. More restrictions are described below.
9799

98-
mod foo {
100+
`use` will create bindings for all [namespaces] from the imported entities, with the exception of a `self` import (described below) which only imports the type namespace.
101+
For example, the following illustrates creating bindings for the same name in two namespaces:
99102

100-
pub mod example {
101-
pub mod iter {}
102-
}
103-
104-
use crate::foo::example::iter; // good: foo is at crate root
105-
// use example::iter; // bad in 2015 edition: relative paths are not allowed without `self`; good in 2018 edition
106-
use self::baz::foobaz; // good: self refers to module 'foo'
107-
use crate::foo::bar::foobar; // good: foo is at crate root
103+
```rust
104+
mod stuff {
105+
pub struct Foo(pub i32);
106+
}
108107

109-
pub mod bar {
110-
pub fn foobar() { }
111-
}
108+
// Imports the `Foo` type and the `Foo` constructor.
109+
use stuff::Foo;
112110

113-
pub mod baz {
114-
use super::bar::foobar; // good: super refers to module 'foo'
115-
pub fn foobaz() { }
116-
}
111+
fn example() {
112+
let ctor = Foo; // From value namespace
113+
let x: Foo = ctor(123);
117114
}
118-
119-
fn main() {}
120115
```
121116

122-
> **Edition Differences**: In the 2015 edition, `use` paths also allow
123-
> accessing items in the crate root. Using the example above, the following
124-
> `use` paths work in 2015 but not 2018:
117+
> **Edition Differences**: In the 2015 edition, `use` paths are relative from the crate root.
118+
> For example:
125119
>
126120
> ```rust,edition2015
127-
> # mod foo {
128-
> # pub mod example { pub mod iter {} }
129-
> # pub mod baz { pub fn foobaz() {} }
130-
> # }
131-
> use foo::example::iter;
132-
> use ::foo::baz::foobaz;
121+
> mod foo {
122+
> pub mod example { pub mod iter {} }
123+
> pub mod baz { pub fn foobaz() {} }
124+
> }
125+
> mod bar {
126+
> // Resolves `foo` from the crate root.
127+
> use foo::example::iter;
128+
> // :: prefix explicitly resolves `foo` from the crate root.
129+
> use ::foo::baz::foobaz;
130+
> }
131+
>
133132
> # fn main() {}
134133
> ```
135134
>
136135
> The 2015 edition does not allow use declarations to reference the [extern prelude].
137-
> Thus [`extern crate`] declarations are still required in 2015 to
138-
> reference an external crate in a use declaration. Beginning with the 2018
139-
> edition, use declarations can specify an external crate dependency the same
140-
> way `extern crate` can.
141-
>
142-
> In the 2018 edition, if an in-scope item has the same name as an external
143-
> crate, then `use` of that crate name requires a leading `::` to
144-
> unambiguously select the crate name. This is to retain compatibility with
145-
> potential future changes. <!-- uniform_paths future-proofing -->
146-
>
147-
> ```rust
148-
> // use std::fs; // Error, this is ambiguous.
149-
> use ::std::fs; // Imports from the `std` crate, not the module below.
150-
> use self::std::fs as self_fs; // Imports the module below.
151-
>
152-
> mod std {
153-
> pub mod fs {}
154-
> }
155-
> # fn main() {}
156-
> ```
136+
> Thus, [`extern crate`] declarations are still required in 2015 to reference an external crate in a `use` declaration.
137+
> Beginning with the 2018 edition, `use` declarations can specify an external crate dependency the same way `extern crate` can.
138+
139+
## `as` renames
140+
141+
The `as` keyword can be used to change the name of an imported entity.
142+
For example:
143+
144+
```rust
145+
// Creates a non-public alias `bar` for the function `foo`.
146+
use inner::foo as bar;
147+
148+
mod inner {
149+
pub fn foo() {}
150+
}
151+
```
152+
153+
## Brace syntax
154+
155+
Braces can be used in the last segment of the path to import multiple entities from the previous segment or the current scope if there are no previous segments.
156+
Braces can be nested, creating a tree of paths, where each grouping of segments is logically combined with its parent to create a full path.
157+
158+
```rust
159+
// Creates bindings to:
160+
// std::collections::BTreeSet
161+
// std::collections::hash_map
162+
// std::collections::hash_map::HashMap
163+
use std::collections::{BTreeSet, hash_map::{self, HashMap}};
164+
```
165+
166+
An empty brace does not import anything. `a::b::{}` is treated as `a::b::{self as _}` and `use {};` has no effect.
167+
168+
> **Edition Differences**: In the 2015 edition, paths are relative to the crate root, so an import such as `use {foo, bar};` will import the names `foo` and `bar` from the crate root, whereas starting in 2018 those names are relative to the current scope.
169+
170+
## `self` imports
171+
172+
The keyword `self` may be used in the [brace syntax](#brace-syntax) to create a binding of the parent entity under its own name.
173+
174+
```rust
175+
mod stuff {
176+
pub fn foo() {}
177+
pub fn bar() {}
178+
}
179+
mod example {
180+
// Creates a binding for `stuff` and `foo`.
181+
use crate::stuff::{self, foo};
182+
pub fn baz() {
183+
foo();
184+
stuff::bar();
185+
}
186+
}
187+
# fn main() {}
188+
```
189+
190+
`self` only creates a binding from the [type namespace] of the parent entity.
191+
For example, in the following, only the `foo` mod is imported:
192+
193+
```rust,compile_fail
194+
mod bar {
195+
pub mod foo {}
196+
pub fn foo() {}
197+
}
198+
199+
// This only imports the module `foo`. The function `foo` lives in
200+
// the value namespace and is not imported.
201+
use bar::foo::{self};
202+
203+
fn main() {
204+
foo(); // Error, `foo` is a module
205+
}
206+
```
207+
208+
> **Note**: `self` as the first segment of a `use` path has a different meaning from `self` inside braces.
209+
> See [`self`] in the paths chapter for more information no the meaning of a leading `self`.
210+
211+
## Glob imports
212+
213+
The `*` character may be used as the last segment of a `use` path to import all importable entities from the entity of the preceding segment.
214+
For example:
215+
216+
```rust
217+
// Creates a non-public alias to `bar`.
218+
use foo::*;
219+
220+
mod foo {
221+
fn i_am_private() {}
222+
enum Example {
223+
V1,
224+
V2,
225+
}
226+
pub fn bar() {
227+
// Creates local aliases to V1 and V2 of the Example enum.
228+
use Example::*;
229+
let x = V1;
230+
}
231+
}
232+
```
233+
234+
Items and named imports are allowed to shadow names from glob imports in the same [namespace].
235+
That is, if there is a name already defined by another item in the same namespace, the glob import will skip it.
236+
For example:
237+
238+
```rust
239+
// This creates a binding to the `clashing::Foo` tuple struct constructor, but
240+
// does not import its type because that would conflict with the `Foo` struct
241+
// defined here.
242+
//
243+
// Note that the order of definition here is unimportant.
244+
use clashing::*;
245+
struct Foo {
246+
field: f32,
247+
}
248+
249+
fn do_stuff() {
250+
// Uses the constructor from clashing::Foo
251+
let f1 = Foo(123);
252+
// The struct expression uses the type from the Foo struct defined above.
253+
let f2 = Foo { field: 1.0 };
254+
// Also imported from the glob import.
255+
let z = Bar {};
256+
}
257+
258+
mod clashing {
259+
pub struct Foo(pub i32);
260+
pub struct Bar {}
261+
}
262+
```
263+
264+
`*` cannot be used as the first or intermediate segments.
265+
`*` cannot be used to import a module's contents into itself (such as `use self::*;`).
266+
267+
> **Edition Differences**: In the 2015 edition, paths are relative to the crate root, so an import such as `use *;` is valid, and it means to import everything from the crate root.
268+
> This cannot be used in the crate root itself.
157269
158270
## Underscore Imports
159271

@@ -199,8 +311,100 @@ m!(use std as _;);
199311
// use std as _;
200312
```
201313

202-
[IDENTIFIER]: ../identifiers.md
314+
## Restrictions
315+
316+
The following are restrictions for valid `use` declarations.
317+
318+
* `use crate;` must use `as` to define the name to bind the crate root to.
319+
* `use {self};` is an error, there must be a leading segment when using `self`.
320+
* As with any item definition, `use` imports cannot create duplicate bindings of the same name in the same namespace in a module or block.
321+
* `use` paths with `$crate` are not allowed in a [`macro_rules`] expansion.
322+
* `use` paths cannot refer to enum variants through a [type alias]. Example:
323+
```rust,compile_fail
324+
enum MyEnum {
325+
MyVariant
326+
}
327+
type TypeAlias = MyEnum;
328+
329+
use MyEnum::MyVariant; // OK
330+
use TypeAlias::MyVariant; // ERROR
331+
```
332+
333+
## Ambiguities
334+
335+
> **Note**: This section is incomplete.
336+
337+
Some situations are an error when there is an ambiguity as to which name a `use` declaration refers to, when there are two name candidates that do not resolve to the same entity.
338+
339+
Glob imports are allowed to import conflicting names in the same namespaces as long as the name is not used or shadowed.
340+
Example:
341+
342+
```rust
343+
mod foo {
344+
pub struct Qux;
345+
}
346+
347+
mod bar {
348+
pub struct Qux;
349+
}
350+
351+
use foo::*;
352+
use bar::*; // Ok, no name conflict.
353+
354+
fn main() {
355+
// This would be an error, due to the ambiguity.
356+
// let x = Qux;
357+
}
358+
```
359+
360+
Multiple glob imports are allowed to import the same name if the imports are of the same item (following re-exports). The visibility of the name is the maximum visibility of the imports. Example:
361+
362+
```rust
363+
mod foo {
364+
pub struct Qux;
365+
}
366+
367+
mod bar {
368+
pub use super::foo::Qux;
369+
}
370+
371+
// These both import the same `Qux`.
372+
// The visibility of `Qux` is `pub` because that is the maximum
373+
// visibility between these two `use` declarations.
374+
use foo::*;
375+
pub use bar::*;
376+
# fn main() {}
377+
```
378+
379+
If an in-scope item has the same name as a crate name in the [extern prelude], then `use` of that crate name requires a leading `::` to unambiguously select the crate name or `crate::` to use the item from the crate root.
380+
381+
```rust,compile_fail
382+
use std::fs; // Error, this is ambiguous.
383+
384+
mod std {
385+
pub mod fs {}
386+
}
387+
# fn main() {}
388+
```
389+
390+
203391
[_SimplePath_]: ../paths.md#simple-paths
204392
[`extern crate`]: extern-crates.md
393+
[`macro_rules`]: ../macros-by-example.md
394+
[`self`]: ../paths.md#self
395+
[associated items]: associated-items.md
396+
[Attributes]: ../attributes.md
397+
[Built-in types]: ../types.md
398+
[Derive macros]: ../procedural-macros.md#derive-macros
399+
[Enum variants]: enumerations.md
205400
[extern prelude]: ../names/preludes.md#extern-prelude
206-
[path qualifiers]: ../paths.md#path-qualifiers
401+
[generic parameters]: generics.md
402+
[IDENTIFIER]: ../identifiers.md
403+
[items]: ../items.md
404+
[local variables]: ../variables.md
405+
[namespace]: ../names/namespaces.md
406+
[namespaces]: ../names/namespaces.md
407+
[paths]: ../paths.md
408+
[tool attributes]: ../attributes.md#tool-attributes
409+
[type alias]: type-aliases.md
410+
[type namespace]: ../names/namespaces.md

src/names/namespaces.md

-2
Original file line numberDiff line numberDiff line change
@@ -99,8 +99,6 @@ A [use declaration] has named aliases that it imports into scope, but the
9999
introduce aliases into multiple namespaces, depending on the item kind being
100100
imported.
101101

102-
<!-- TODO: describe how `use` works on the use-declarations page, and link to it here. -->
103-
104102
## Sub-namespaces
105103

106104
The macro namespace is split into two sub-namespaces: one for [bang-style macros] and one for [attributes].

0 commit comments

Comments
 (0)