Skip to content

Commit c99db24

Browse files
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 a834b2a commit c99db24

File tree

2 files changed

+261
-59
lines changed

2 files changed

+261
-59
lines changed

src/items/use-declarations.md

Lines changed: 261 additions & 57 deletions
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
@@ -87,75 +88,186 @@ In this example, the module `quux` re-exports two public names defined in
8788

8889
## `use` Paths
8990

90-
> **Note**: This section is incomplete.
91+
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.
92+
They may create bindings for:
9193

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

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

100-
mod foo {
102+
`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.
103+
For example, the following illustrates creating bindings for the same name in two namespaces:
101104

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

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

115-
pub mod baz {
116-
use super::bar::foobar; // good: super refers to module 'foo'
117-
pub fn foobaz() { }
118-
}
113+
fn example() {
114+
let ctor = Foo; // From value namespace
115+
let x: Foo = ctor(123);
119116
}
120-
121-
fn main() {}
122117
```
123118

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

@@ -201,8 +313,100 @@ m!(use std as _;);
201313
// use std as _;
202314
```
203315

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

src/names/namespaces.md

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -100,8 +100,6 @@ A [use declaration] has named aliases that it imports into scope, but the
100100
introduce aliases into multiple namespaces, depending on the item kind being
101101
imported.
102102

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

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

0 commit comments

Comments
 (0)