-
Notifications
You must be signed in to change notification settings - Fork 273
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
Elaborate on lifetime in iter.next() in 3.6 IterMut #43
Comments
Are you asking a question or do you want the article to include more clarification? In other words, are you unsure what is meant here, or do you already know and just want to extend the article? I am not entirely sure. 😄 |
@jonastepe |
Maybe I should first repost my deleted former post ... Does that help you?
That is not the sole purpose of specifying lifetimes. Mainly, it is to relate how borrows in a function/method call or complex type are related to another. You communicate your intention to the compiler, so it can reason with your intentions in mind and decide if those comply with its safety rules. In the desugared example provided here: impl<'a, T> Iterator for Iter<'a, T> {
type Item = &'a T;
fn next<'b>(&'b mut self) -> Option<&'a T> { /* stuff */ }
} We can see that the borrow of The borrow of let x = iter.next().unwrap(); The returned reference is of the lifetime Let's assume it would last longer and the method signature looked like this (Note, that you cannot do that with today's Rust, since the Iterator trait specifies the above signature): fn next<'a>(&'a mut self) -> Option<&'a T>; Now I convey to the compiler, that I want the two lifetimes/borrows to be linked. So, if I call let x = iter.next().unwrap();
let y = iter.next().unwrap(); // error, more than one mutable borrow of iter! The It is also unnecessary. What the author, @gankro, does here, is setting the stage in order to emphasize the difference to |
@jonastepe |
Sure you may 😉. I think the book as it stands need a lot more content and explanations. Datastructures in Rust are a kind of a special topic because of its ownership rules. I think in the future we should provide implementation examples for other datastructures as well. |
I feel there's a gap of logic here. IIUC lifetime is meant to restrain the scope of output relative to input, and it is not intuitive how it would prevent
next()
to be called consecutively.The specific example of
would directly lead to the conclusion that
Option<&'a T>
lives as long asT
lives, which is until that element isdrop()
ed or the whole list is dead. The key difference fromOption<&'b T>
would be when the element isdrop()
ed.What happens when
next()
is called the second (and third) time?The text was updated successfully, but these errors were encountered: