diff --git a/src/items/use-declarations.md b/src/items/use-declarations.md index d01ab6a767..49781895c8 100644 --- a/src/items/use-declarations.md +++ b/src/items/use-declarations.md @@ -203,6 +203,21 @@ mod example { > [!NOTE] > `self` may also be used as the first segment of a path. The use of `self` as the first segment and inside a `use` brace is logically the same; it means the current module of the parent segment, or the current module if there is no parent segment. See [`self`] in the paths chapter for more information on the meaning of a leading `self`. +r[items.use.self.trailing] +`self` may appear as the last segment of a `use` path, preceded by `::`. A path of the form `P::self` is equivalent to `P::{self}`, and `P::self as name` is equivalent to `P::{self as name}`. + +```rust +mod m { + pub enum E { V1, V2 } +} +use m::self as _; // Equivalent to `use m::{self as _};`. +use m::E::self; // Equivalent to `use m::E::{self};`. +# fn main() {} +``` + +> [!NOTE] +> See [paths.qualifiers.mod-self.trailing] for restrictions on the preceding path. + r[items.use.self.module] When `self` is used within [brace syntax], the path preceding the brace group must resolve to a [module], [enumeration], or [trait]. diff --git a/src/paths.md b/src/paths.md index 3df5b5e02f..7f8ca41665 100644 --- a/src/paths.md +++ b/src/paths.md @@ -233,7 +233,30 @@ r[paths.qualifiers.mod-self.intro] `self` resolves the path relative to the current module. r[paths.qualifiers.mod-self.restriction] -`self` can only be used as the first segment, without a preceding `::`. +`self` may only be used as the first segment of a path (without a preceding `::`) or as the last segment (preceded by `::`). + +r[paths.qualifiers.mod-self.trailing] +When `self` appears as the last segment of a path, it refers to the entity named by the preceding segment. The preceding path must resolve to a [module], [enumeration], or [trait]. + +```rust +mod m { + pub enum E { V1 } + pub trait Tr {} + pub(in crate::m::self) fn g() {} // OK: Modules can be parents of `self`. +} +type Ty = m::E::self; // OK: Enumerations can be parents of `self`. +fn f() {} // OK: Traits can be parents of `self`. +# fn main() { let _: Ty = m::E::V1; } +``` + +```rust,compile_fail,E0223 +struct S; +type Ty = S::self; // ERROR: Structs cannot be parents of `self`. +# fn main() {} +``` + +> [!NOTE] +> See [items.use.self] for additional rules about `self` in `use` declarations. r[paths.qualifiers.self-pat] In a method body, a path which consists of a single `self` segment resolves to the method's self parameter. @@ -482,6 +505,7 @@ mod without { // crate::without [macro transcribers]: macros-by-example.md [macros]: macros.md [mbe]: macros-by-example.md +[module]: items/modules.md [patterns]: patterns.md [struct]: items/structs.md [trait implementations]: items/implementations.md#trait-implementations