Book: 'static lifetime & trait objects

Created on 8 Jun 2017  ·  4Comments  ·  Source: rust-lang/book

I bumped into some issues with using trait objects and I was informed by other nice Rust folks that I have to add 'static lifetime to my trait for this to work. I was quite puzzled since according the book 'static lifetime means "to exist throughout the lifetime of the program" but it does not say that it has different meaning when you associate it with traits. I think it would be very helpful if the book explained what 'static means to traits.

Enhancement

Most helpful comment

According to https://doc.rust-lang.org/book/index.html:

The “Advanced Lifetimes” section in Chapter 19 was removed because compiler improvements have made the constructs in that section even rarer.

While that may be true that it's rare, this specific issue is still relevant and it would be good to have some explanation about it in the book.

All 4 comments

Seems this has been addressed already in the 2nd edition draft: https://doc.rust-lang.org/book/second-edition/ch19-02-advanced-lifetimes.html

Types with no references count as T: 'static. Because 'static means the reference must live as long as the entire program, a type that contains no references meets the criteria of all references living as long as the entire program (since there are no references). Think of it this way: if the borrow checker is concerned about references living long enough, then there's no real distinction between a type that has no references and a type that has references that live forever; both of them are the same for the purpose of determining whether or not a reference has a shorter lifetime than what it refers to.

This section is no longer in the book, as far as i can tell. I couldn't find any other explanation of how 'static is used with trait objects.

I would find it really useful if this was in the book, because it's not at all intuitively obvious, even if you know the basics of what lifetimes and trait objects are.

Indeed.

According to https://doc.rust-lang.org/book/index.html:

The “Advanced Lifetimes” section in Chapter 19 was removed because compiler improvements have made the constructs in that section even rarer.

While that may be true that it's rare, this specific issue is still relevant and it would be good to have some explanation about it in the book.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

carols10cents picture carols10cents  ·  5Comments

ctsa picture ctsa  ·  3Comments

mikebenfield picture mikebenfield  ·  3Comments

icanrealizeum picture icanrealizeum  ·  3Comments

xStrom picture xStrom  ·  3Comments