Skip to content

Commit 32a63f0

Browse files
document default object lifetime bounds, rfc 599 and rfc 1156
1 parent b060f73 commit 32a63f0

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

src/types.md

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -340,6 +340,52 @@ fn main() {
340340
In this example, the trait `Printable` occurs as a trait object in both the
341341
type signature of `print`, and the cast expression in `main`.
342342

343+
Since a trait object can contain references, the lifetimes of those references
344+
need to be expressed as part of the trait object. The assumed lifetime of
345+
references held by a trait object is called its _default object lifetime bound_.
346+
These were defined in [RFC 599] and amended in [RFC 1156].
347+
348+
[RFC 599]: https://github.com/rust-lang/rfcs/blob/master/text/0599-default-object-bound.md
349+
[RFC 1156]: https://github.com/rust-lang/rfcs/blob/master/text/1156-adjust-default-object-bounds.md
350+
351+
For traits that themselves have no lifetime parameters, the default bound is
352+
based on what kind of trait object is used:
353+
354+
```rust,ignore
355+
// For the following trait...
356+
trait Foo { }
357+
358+
// ...these two are the same:
359+
Box<Foo>
360+
Box<Foo + 'static>
361+
362+
// ...and so are these:
363+
&'a Foo
364+
&'a (Foo + 'a)
365+
```
366+
367+
The `+ 'static` and `+ 'a` refer to the default bounds of those kinds of trait
368+
objects, and also to how you can directly override them. Note that the innermost
369+
object sets the bound, so `&'a Box<Foo>` is still `&'a Box<Foo + 'static>`.
370+
371+
For traits that have lifetime parameters of their own, the default bound is
372+
based on that lifetime parameter:
373+
374+
```rust,ignore
375+
// For the following trait...
376+
trait Bar<'a>: 'a { }
377+
378+
// ...these two are the same:
379+
Box<Bar<'a>>
380+
Box<Bar<'a> + 'a>
381+
```
382+
383+
The default for user-defined trait objects is based on the object type itself.
384+
If a type parameter has a lifetime bound, then that lifetime bound becomes the
385+
default bound for trait objects of that type. For example, `std::cell::Ref<'a,
386+
T>` contains a `T: 'a` bound, therefore trait objects of type `Ref<'a,
387+
SomeTrait>` are the same as `Ref<'a, (SomeTrait + 'a)>`.
388+
343389
### Type parameters
344390

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

0 commit comments

Comments
 (0)