]> git.proxmox.com Git - rustc.git/blob - src/doc/reference/src/items/use-declarations.md
New upstream version 1.44.1+dfsg1
[rustc.git] / src / doc / reference / src / items / use-declarations.md
1 # Use declarations
2
3 > **<sup>Syntax:</sup>**\
4 > _UseDeclaration_ :\
5 > &nbsp;&nbsp; `use` _UseTree_ `;`
6 >
7 > _UseTree_ :\
8 > &nbsp;&nbsp; &nbsp;&nbsp; ([_SimplePath_]<sup>?</sup> `::`)<sup>?</sup> `*`\
9 > &nbsp;&nbsp; | ([_SimplePath_]<sup>?</sup> `::`)<sup>?</sup> `{` (_UseTree_ ( `,` _UseTree_ )<sup>\*</sup> `,`<sup>?</sup>)<sup>?</sup> `}`\
10 > &nbsp;&nbsp; | [_SimplePath_]&nbsp;( `as` ( [IDENTIFIER] | `_` ) )<sup>?</sup>
11
12 A _use declaration_ creates one or more local name bindings synonymous with
13 some other [path]. Usually a `use` declaration is used to shorten the path
14 required to refer to a module item. These declarations may appear in [modules]
15 and [blocks], usually at the top.
16
17 [path]: ../paths.md
18 [modules]: modules.md
19 [blocks]: ../expressions/block-expr.md
20
21 Use declarations support a number of convenient shortcuts:
22
23 * 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 * Simultaneously binding a list of paths with a common prefix and their common
26 parent module, using the `self` keyword, such as `use a::b::{self, c, d::e};`
27 * Rebinding the target name as a new local name, using the syntax `use p::q::r
28 as x;`. This can also be used with the last two features:
29 `use a::b::{self as ab, c as abc}`.
30 * Binding all paths matching a given prefix, using the asterisk wildcard syntax
31 `use a::b::*;`.
32 * Nesting groups of the previous features multiple times, such as
33 `use a::b::{self as ab, c, d::{*, e::f}};`
34
35 An example of `use` declarations:
36
37 ```rust
38 use std::option::Option::{Some, None};
39 use std::collections::hash_map::{self, HashMap};
40
41 fn foo<T>(_: T){}
42 fn bar(map1: HashMap<String, usize>, map2: hash_map::HashMap<String, usize>){}
43
44 fn main() {
45 // Equivalent to 'foo(vec![std::option::Option::Some(1.0f64),
46 // std::option::Option::None]);'
47 foo(vec![Some(1.0f64), None]);
48
49 // Both `hash_map` and `HashMap` are in scope.
50 let map1 = HashMap::new();
51 let map2 = hash_map::HashMap::new();
52 bar(map1, map2);
53 }
54 ```
55
56 ## `use` Visibility
57
58 Like items, `use` declarations are private to the containing module, by
59 default. Also like items, a `use` declaration can be public, if qualified by
60 the `pub` keyword. Such a `use` declaration serves to _re-export_ a name. A
61 public `use` declaration can therefore _redirect_ some public name to a
62 different target definition: even a definition with a private canonical path,
63 inside a different module. If a sequence of such redirections form a cycle or
64 cannot be resolved unambiguously, they represent a compile-time error.
65
66 An example of re-exporting:
67
68 ```rust
69 mod quux {
70 pub use self::foo::{bar, baz};
71 pub mod foo {
72 pub fn bar() {}
73 pub fn baz() {}
74 }
75 }
76
77 fn main() {
78 quux::bar();
79 quux::baz();
80 }
81 ```
82
83 In this example, the module `quux` re-exports two public names defined in
84 `foo`.
85
86 ## `use` Paths
87
88 > **Note**: This section is incomplete.
89
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
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
97
98 mod foo {
99
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
108
109 pub mod bar {
110 pub fn foobar() { }
111 }
112
113 pub mod baz {
114 use super::bar::foobar; // good: super refers to module 'foo'
115 pub fn foobaz() { }
116 }
117 }
118
119 fn main() {}
120 ```
121
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:
125 >
126 > ```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;
133 > # fn main() {}
134 > ```
135 >
136 > 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,edition2018
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 > ```
157
158 ## Underscore Imports
159
160 Items can be imported without binding to a name by using an underscore with
161 the form `use path as _`. This is particularly useful to import a trait so
162 that its methods may be used without importing the trait's symbol, for example
163 if the trait's symbol may conflict with another symbol. Another example is to
164 link an external crate without importing its name.
165
166 Asterisk glob imports will import items imported with `_` in their unnameable
167 form.
168
169 ```rust
170 mod foo {
171 pub trait Zoo {
172 fn zoo(&self) {}
173 }
174
175 impl<T> Zoo for T {}
176 }
177
178 use self::foo::Zoo as _;
179 struct Zoo; // Underscore import avoids name conflict with this item.
180
181 fn main() {
182 let z = Zoo;
183 z.zoo();
184 }
185 ```
186
187 The unique, unnameable symbols are created after macro expansion so that
188 macros may safely emit multiple references to `_` imports. For example, the
189 following should not produce an error:
190
191 ```rust
192 macro_rules! m {
193 ($item: item) => { $item $item }
194 }
195
196 m!(use std as _;);
197 // This expands to:
198 // use std as _;
199 // use std as _;
200 ```
201
202 [IDENTIFIER]: ../identifiers.md
203 [_SimplePath_]: ../paths.md#simple-paths
204 [`extern crate`]: extern-crates.md
205 [extern prelude]: extern-crates.md#extern-prelude
206 [path qualifiers]: ../paths.md#path-qualifiers