Skip to content

Commit 571a120

Browse files
committed
Parenthesized paths in trait objects
1 parent ca73087 commit 571a120

File tree

1 file changed

+12
-3
lines changed

1 file changed

+12
-3
lines changed

src/types.md

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -511,7 +511,7 @@ Because captures are often by reference, the following general rules arise:
511511
> &nbsp;&nbsp; `dyn`<sup>?</sup> _LifetimeOrPath_ ( `+` _LifetimeOrPath_ )<sup>\*</sup> `+`<sup>?</sup>
512512
>
513513
> _LifetimeOrPath_ :
514-
> &nbsp;&nbsp; [_Path_] | [_LIFETIME_OR_LABEL_]
514+
> &nbsp;&nbsp; [_Path_] | `(` [_Path_] `)` | [_LIFETIME_OR_LABEL_]
515515
516516
A *trait object* is an opaque value of another type that implements a set of
517517
traits. The set of traits is made up of an [object safe] *base trait* plus any
@@ -523,8 +523,10 @@ of the base trait.
523523
Trait objects are written as the optional keyword `dyn` followed by a set of
524524
trait bounds, but with the following restrictions on the trait bounds. All
525525
traits except the first trait must be auto traits, there may not be more than
526-
one lifetime, and opt-out bounds (e.g. `?sized`) are not allowed. For example,
527-
given a trait `Trait`, the following are all trait objects:
526+
one lifetime, and opt-out bounds (e.g. `?sized`) are not allowed. Furthermore,
527+
paths to traits may be parenthesized.
528+
529+
For example, given a trait `Trait`, the following are all trait objects:
528530

529531
* `Trait`
530532
* `dyn Trait`
@@ -534,6 +536,13 @@ given a trait `Trait`, the following are all trait objects:
534536
* `dyn Trait + Send + 'static`
535537
* `dyn Trait +`
536538
* `dyn 'static + Trait`.
539+
* `dyn (Trait)`
540+
541+
If the first bound of the trait object is a path that starts with `::`, then the
542+
`dyn` will be treated as a part of the path. The first path can be put in
543+
parenthesis to get around this. As such, if you want a trait object with the
544+
trait `::your_module::Trait`, you should write it as
545+
`dyn (::your_module::Trait)`.
537546

538547
> Note: For clarity, it is recommended to always use the `dyn` keyword on your
539548
> trait objects unless your codebase supports compiling with Rust 1.26 or lower.

0 commit comments

Comments
 (0)