Skip to content

Explain default trait object liftime bounds. #31353

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions src/doc/reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -3603,6 +3603,45 @@ fn main() {
In this example, the trait `Printable` occurs as a trait object in both the
type signature of `print`, and the cast expression in `main`.

Trait objects may contain references, and so those references will need a
lifetime:

```rust,ignore
// Some trait like this...
trait Bar<'a>: 'a { }

// ... means these are the same:
Box<Bar>
Box<Bar + 'a>
```

If there’s no bound, then the default lifetime is the same as the pointer that
the trait object is behind:

```rust,ignore
// Some trait like this...
trait Bar { }

// ... means these are the same:
&'a Bar
&'a (Bar + 'a)
```

In any other case, the default is `'static`:

```rust,ignore
// Some trait like this...
trait Bar { }

// ... means these are the same:
Box<Bar>
Box<Bar + 'static>
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

one case you may want to clarify is that &Box<Bar> is same as &Box<Bar+'static> -- i.e., it's the innermost case that matters

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

there is technically I think one other rule, not sure how much detail we want to go into though. I think if you have struct Ref<'a, T: ?Sized> and you do Ref<'a, Trait> you get Ref<'a, Trait+'a> by default. Unless we changed that in the follow-up RFC. :P I guess I should go double check.


// and so are these:
&'a Box<Bar>
&'a Box<Bar + 'static>
```

### Type parameters

Within the body of an item that has type parameter declarations, the names of
Expand Down