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