You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
[^bare-2021]: See [type.trait-object.syntax-edition2021].
12
+
[^dyn-2018]: See [type.trait-object.syntax-edition2018].
13
+
11
14
r[type.trait-object.intro]
12
15
A *trait object* is an opaque value of another type that implements a set of traits. The set of traits is made up of a [dyn compatible]*base trait* plus any number of [auto traits].
13
16
14
17
r[type.trait-object.impls]
15
18
Trait objects implement the base trait, its auto traits, and any [supertraits] of the base trait.
16
19
17
-
r[type.trait-object.name]
18
-
Trait objects are written as the keyword `dyn` followed by a set of trait bounds, but with the following restrictions on the trait bounds.
19
-
20
-
r[type.trait-object.constraint]
21
-
There may not be more than one non-auto trait, no more than one lifetime, and opt-out bounds (e.g. `?Sized`) are not allowed. Furthermore, paths to traits may be parenthesized.
20
+
r[type.trait-object.bounds]
21
+
There must be at least one trait bound, there may not be more than one non-auto trait, no more than one lifetime, and opt-out bounds (e.g., `?Sized`) and `use<..>` bounds are not allowed.
22
22
23
23
For example, given a trait `Trait`, the following are all trait objects:
24
24
@@ -33,11 +33,13 @@ For example, given a trait `Trait`, the following are all trait objects:
33
33
34
34
r[type.trait-object.syntax-edition2021]
35
35
> [!EDITION-2021]
36
-
> Before the 2021 edition, the `dyn` keyword may be omitted.
36
+
> Before the 2021 edition, the `dyn` keyword may be omitted. In the 2021 edition and beyond, the `dyn` keyword is required semantically.
37
37
38
38
r[type.trait-object.syntax-edition2018]
39
39
> [!EDITION-2018]
40
-
> In the 2015 edition, if the first bound of the trait object is a path that starts with `::`, then the `dyn` will be treated as a part of the path. The first path can be put in parenthesis to get around this. As such, if you want a trait object with the trait `::your_module::Trait`, you should write it as `dyn (::your_module::Trait)`.
40
+
> In the 2015 edition, `dyn` must be followed by [PathIdentSegment], [LIFETIME_TOKEN], `for`, `(` or `?` to be interpreted as a keyword instead of a regular identifier.
41
+
>
42
+
> Most notably, `dyn`, `dyn::T` and `dyn<T>` will all be treated as type paths. As such, if you want a trait object type with the trait `::module::Trait`, you need to put the path in parentheses and write it as `dyn (::module::Trait)`.
41
43
>
42
44
> Beginning in the 2018 edition, `dyn` is a true keyword and is not allowed in paths, so the parentheses are not necessary.
0 commit comments