]> git.proxmox.com Git - rustc.git/blob - src/doc/reference/src/paths.md
New upstream version 1.54.0+dfsg1
[rustc.git] / src / doc / reference / src / paths.md
1 # Paths
2
3 A *path* is a sequence of one or more path segments _logically_ separated by
4 a namespace <span class="parenthetical">qualifier (`::`)</span>. If a path
5 consists of only one segment, it refers to either an [item] or a [variable] in
6 a local control scope. If a path has multiple segments, it always refers to an
7 item.
8
9 Two examples of simple paths consisting of only identifier segments:
10
11 <!-- ignore: syntax fragment -->
12 ```rust,ignore
13 x;
14 x::y::z;
15 ```
16
17 ## Types of paths
18
19 ### Simple Paths
20
21 > **<sup>Syntax</sup>**\
22 > _SimplePath_ :\
23 > &nbsp;&nbsp; `::`<sup>?</sup> _SimplePathSegment_ (`::` _SimplePathSegment_)<sup>\*</sup>
24 >
25 > _SimplePathSegment_ :\
26 > &nbsp;&nbsp; [IDENTIFIER] | `super` | `self` | `crate` | `$crate`
27
28 Simple paths are used in [visibility] markers, [attributes], [macros], and [`use`] items.
29 Examples:
30
31 ```rust
32 use std::io::{self, Write};
33 mod m {
34 #[clippy::cyclomatic_complexity = "0"]
35 pub (in super) fn f1() {}
36 }
37 ```
38
39 ### Paths in expressions
40
41 > **<sup>Syntax</sup>**\
42 > _PathInExpression_ :\
43 > &nbsp;&nbsp; `::`<sup>?</sup> _PathExprSegment_ (`::` _PathExprSegment_)<sup>\*</sup>
44 >
45 > _PathExprSegment_ :\
46 > &nbsp;&nbsp; _PathIdentSegment_ (`::` _GenericArgs_)<sup>?</sup>
47 >
48 > _PathIdentSegment_ :\
49 > &nbsp;&nbsp; [IDENTIFIER] | `super` | `self` | `Self` | `crate` | `$crate`
50 >
51 > _GenericArgs_ :\
52 > &nbsp;&nbsp; &nbsp;&nbsp; `<` `>`\
53 > &nbsp;&nbsp; | `<` ( _GenericArg_ `,` )<sup>\*</sup> _GenericArg_ `,`<sup>?</sup> `>`
54 >
55 > _GenericArg_ :\
56 > &nbsp;&nbsp; [_Lifetime_] | [_Type_] | _GenericArgsConst_ | _GenericArgsBinding_
57 >
58 > _GenericArgsConst_ :\
59 > &nbsp;&nbsp; &nbsp;&nbsp; [_BlockExpression_]\
60 > &nbsp;&nbsp; | [_LiteralExpression_]\
61 > &nbsp;&nbsp; | `-` [_LiteralExpression_]\
62 > &nbsp;&nbsp; | [_SimplePathSegment_]
63 >
64 > _GenericArgsBinding_ :\
65 > &nbsp;&nbsp; [IDENTIFIER] `=` [_Type_]
66
67 Paths in expressions allow for paths with generic arguments to be specified. They are
68 used in various places in [expressions] and [patterns].
69
70 The `::` token is required before the opening `<` for generic arguments to avoid
71 ambiguity with the less-than operator. This is colloquially known as "turbofish" syntax.
72
73 ```rust
74 (0..10).collect::<Vec<_>>();
75 Vec::<u8>::with_capacity(1024);
76 ```
77
78 The order of generic arguments is restricted to lifetime arguments, then type
79 arguments, then const arguments, then equality constraints.
80
81 Const arguments must be surrounded by braces unless they are a
82 [literal] or a single segment path.
83
84 ## Qualified paths
85
86 > **<sup>Syntax</sup>**\
87 > _QualifiedPathInExpression_ :\
88 > &nbsp;&nbsp; _QualifiedPathType_ (`::` _PathExprSegment_)<sup>+</sup>
89 >
90 > _QualifiedPathType_ :\
91 > &nbsp;&nbsp; `<` [_Type_] (`as` _TypePath_)? `>`
92 >
93 > _QualifiedPathInType_ :\
94 > &nbsp;&nbsp; _QualifiedPathType_ (`::` _TypePathSegment_)<sup>+</sup>
95
96 Fully qualified paths allow for disambiguating the path for [trait implementations] and
97 for specifying [canonical paths](#canonical-paths). When used in a type specification, it
98 supports using the type syntax specified below.
99
100 ```rust
101 struct S;
102 impl S {
103 fn f() { println!("S"); }
104 }
105 trait T1 {
106 fn f() { println!("T1 f"); }
107 }
108 impl T1 for S {}
109 trait T2 {
110 fn f() { println!("T2 f"); }
111 }
112 impl T2 for S {}
113 S::f(); // Calls the inherent impl.
114 <S as T1>::f(); // Calls the T1 trait function.
115 <S as T2>::f(); // Calls the T2 trait function.
116 ```
117
118 ### Paths in types
119
120 > **<sup>Syntax</sup>**\
121 > _TypePath_ :\
122 > &nbsp;&nbsp; `::`<sup>?</sup> _TypePathSegment_ (`::` _TypePathSegment_)<sup>\*</sup>
123 >
124 > _TypePathSegment_ :\
125 > &nbsp;&nbsp; _PathIdentSegment_ `::`<sup>?</sup> ([_GenericArgs_] | _TypePathFn_)<sup>?</sup>
126 >
127 > _TypePathFn_ :\
128 > `(` _TypePathFnInputs_<sup>?</sup> `)` (`->` [_Type_])<sup>?</sup>
129 >
130 > _TypePathFnInputs_ :\
131 > [_Type_] (`,` [_Type_])<sup>\*</sup> `,`<sup>?</sup>
132
133 Type paths are used within type definitions, trait bounds, type parameter bounds,
134 and qualified paths.
135
136 Although the `::` token is allowed before the generics arguments, it is not required
137 because there is no ambiguity like there is in _PathInExpression_.
138
139 ```rust
140 # mod ops {
141 # pub struct Range<T> {f1: T}
142 # pub trait Index<T> {}
143 # pub struct Example<'a> {f1: &'a i32}
144 # }
145 # struct S;
146 impl ops::Index<ops::Range<usize>> for S { /*...*/ }
147 fn i<'a>() -> impl Iterator<Item = ops::Example<'a>> {
148 // ...
149 # const EXAMPLE: Vec<ops::Example<'static>> = Vec::new();
150 # EXAMPLE.into_iter()
151 }
152 type G = std::boxed::Box<dyn std::ops::FnOnce(isize) -> isize>;
153 ```
154
155 ## Path qualifiers
156
157 Paths can be denoted with various leading qualifiers to change the meaning of
158 how it is resolved.
159
160 ### `::`
161
162 Paths starting with `::` are considered to be *global paths* where the segments of the path
163 start being resolved from a place which differs based on edition. Each identifier in
164 the path must resolve to an item.
165
166 > **Edition Differences**: In the 2015 Edition, identifiers resolve from the "crate root"
167 > (`crate::` in the 2018 edition), which contains a variety of different items, including
168 > external crates, default crates such as `std` or `core`, and items in the top level of
169 > the crate (including `use` imports).
170 >
171 > Beginning with the 2018 Edition, paths starting with `::` resolve from
172 > crates in the [extern prelude]. That is, they must be followed by the name of a crate.
173
174 ```rust
175 mod a {
176 pub fn foo() {}
177 }
178 mod b {
179 pub fn foo() {
180 ::a::foo(); // call `a`'s foo function
181 // In Rust 2018, `::a` would be interpreted as the crate `a`.
182 }
183 }
184 # fn main() {}
185 ```
186
187 ### `self`
188
189 `self` resolves the path relative to the current module. `self` can only be used as the
190 first segment, without a preceding `::`.
191
192 ```rust
193 fn foo() {}
194 fn bar() {
195 self::foo();
196 }
197 # fn main() {}
198 ```
199
200 ### `Self`
201
202 `Self`, with a capital "S", is used to refer to the implementing type within
203 [traits] and [implementations].
204
205 `Self` can only be used as the first segment, without a preceding `::`.
206
207 ```rust
208 trait T {
209 type Item;
210 const C: i32;
211 // `Self` will be whatever type that implements `T`.
212 fn new() -> Self;
213 // `Self::Item` will be the type alias in the implementation.
214 fn f(&self) -> Self::Item;
215 }
216 struct S;
217 impl T for S {
218 type Item = i32;
219 const C: i32 = 9;
220 fn new() -> Self { // `Self` is the type `S`.
221 S
222 }
223 fn f(&self) -> Self::Item { // `Self::Item` is the type `i32`.
224 Self::C // `Self::C` is the constant value `9`.
225 }
226 }
227 ```
228
229 ### `super`
230
231 `super` in a path resolves to the parent module. It may only be used in leading
232 segments of the path, possibly after an initial `self` segment.
233
234 ```rust
235 mod a {
236 pub fn foo() {}
237 }
238 mod b {
239 pub fn foo() {
240 super::a::foo(); // call a's foo function
241 }
242 }
243 # fn main() {}
244 ```
245
246 `super` may be repeated several times after the first `super` or `self` to refer to
247 ancestor modules.
248
249 ```rust
250 mod a {
251 fn foo() {}
252
253 mod b {
254 mod c {
255 fn foo() {
256 super::super::foo(); // call a's foo function
257 self::super::super::foo(); // call a's foo function
258 }
259 }
260 }
261 }
262 # fn main() {}
263 ```
264
265 ### `crate`
266
267 `crate` resolves the path relative to the current crate. `crate` can only be used as the
268 first segment, without a preceding `::`.
269
270 ```rust
271 fn foo() {}
272 mod a {
273 fn bar() {
274 crate::foo();
275 }
276 }
277 # fn main() {}
278 ```
279
280 ### `$crate`
281
282 `$crate` is only used within [macro transcribers], and can only be used as the first
283 segment, without a preceding `::`. `$crate` will expand to a path to access items from the
284 top level of the crate where the macro is defined, regardless of which crate the macro is
285 invoked.
286
287 ```rust
288 pub fn increment(x: u32) -> u32 {
289 x + 1
290 }
291
292 #[macro_export]
293 macro_rules! inc {
294 ($x:expr) => ( $crate::increment($x) )
295 }
296 # fn main() { }
297 ```
298
299 ## Canonical paths
300
301 Items defined in a module or implementation have a *canonical path* that
302 corresponds to where within its crate it is defined. All other paths to these
303 items are aliases. The canonical path is defined as a *path prefix* appended by
304 the path segment the item itself defines.
305
306 [Implementations] and [use declarations] do not have canonical paths, although
307 the items that implementations define do have them. Items defined in
308 block expressions do not have canonical paths. Items defined in a module that
309 does not have a canonical path do not have a canonical path. Associated items
310 defined in an implementation that refers to an item without a canonical path,
311 e.g. as the implementing type, the trait being implemented, a type parameter or
312 bound on a type parameter, do not have canonical paths.
313
314 The path prefix for modules is the canonical path to that module. For bare
315 implementations, it is the canonical path of the item being implemented
316 surrounded by <span class="parenthetical">angle (`<>`)</span> brackets. For
317 [trait implementations], it is the canonical path of the item being implemented
318 followed by `as` followed by the canonical path to the trait all surrounded in
319 <span class="parenthetical">angle (`<>`)</span> brackets.
320
321 The canonical path is only meaningful within a given crate. There is no global
322 namespace across crates; an item's canonical path merely identifies it within
323 the crate.
324
325 ```rust
326 // Comments show the canonical path of the item.
327
328 mod a { // ::a
329 pub struct Struct; // ::a::Struct
330
331 pub trait Trait { // ::a::Trait
332 fn f(&self); // ::a::Trait::f
333 }
334
335 impl Trait for Struct {
336 fn f(&self) {} // <::a::Struct as ::a::Trait>::f
337 }
338
339 impl Struct {
340 fn g(&self) {} // <::a::Struct>::g
341 }
342 }
343
344 mod without { // ::without
345 fn canonicals() { // ::without::canonicals
346 struct OtherStruct; // None
347
348 trait OtherTrait { // None
349 fn g(&self); // None
350 }
351
352 impl OtherTrait for OtherStruct {
353 fn g(&self) {} // None
354 }
355
356 impl OtherTrait for ::a::Struct {
357 fn g(&self) {} // None
358 }
359
360 impl ::a::Trait for OtherStruct {
361 fn f(&self) {} // None
362 }
363 }
364 }
365
366 # fn main() {}
367 ```
368
369 [_BlockExpression_]: expressions/block-expr.md
370 [_Expression_]: expressions.md
371 [_GenericArgs_]: #paths-in-expressions
372 [_Lifetime_]: trait-bounds.md
373 [_LiteralExpression_]: expressions/literal-expr.md
374 [_SimplePathSegment_]: #simple-paths
375 [_Type_]: types.md#type-expressions
376 [literal]: expressions/literal-expr.md
377 [item]: items.md
378 [variable]: variables.md
379 [implementations]: items/implementations.md
380 [use declarations]: items/use-declarations.md
381 [IDENTIFIER]: identifiers.md
382 [`use`]: items/use-declarations.md
383 [attributes]: attributes.md
384 [expressions]: expressions.md
385 [extern prelude]: names/preludes.md#extern-prelude
386 [macro transcribers]: macros-by-example.md
387 [macros]: macros-by-example.md
388 [patterns]: patterns.md
389 [trait implementations]: items/implementations.md#trait-implementations
390 [traits]: items/traits.md
391 [visibility]: visibility-and-privacy.md