Understanding Rust Lifetimes
Video Statistics and Information
Channel: Ryan Levick
Views: 15,107
Rating: 4.9698114 out of 5
Keywords:
Id: MSi3E5Z8oRw
Channel Id: undefined
Length: 81min 6sec (4866 seconds)
Published: Mon Nov 02 2020
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.
This was great, but please help me crystallize the lesson in my brain because a couple things may not have actually been stated explicitly (or I missed it, so please forgive me). I have two questions:
impl
? (Seems like a nice feature.)std::mem::replace()
(or possibly similarstd::mem
workarounds), or are there other examples of clever workarounds?Thanks!
EDIT: wrong godbolt link
(first time posting a comment on reddit after lurking here for many years, but I'm getting back to Rust and not understanding the detailed behind-the-scenes really bugs me)
I loved the video as it made me think more deeply about the lifetimes. What irks me here, though, is that to me this doesn't feel like a solution but more of a hack/workaround. Could there be a "more proper" way to communicate to the compiler that
self.slice
really has a lifetime of'iter
?&'iter mut T
in existence?I don't mean this as a dig at Ryan (the stream author) but more of could we find/create a better way? Using
std::mem::replace
seems like hiding the unsafe (and possibly dangerous) operation of making the compiler forget the lifetime and assigning it our own behind a "safe" face. In that case I think usingunsafe
, e.g. like this:would be much more clear on what is actually going on without hiding it behind the jargon of
std::mem::replace
.Also looking at the assembly (https://godbolt.org/z/M4oa3f), the
std::mem::replace
seems to be doing unnecessary work when all we want is to just adjust the semantics of the compiler.Btw, maybe a dumb question, as I read it it seems that generic types do not include lifetimes? Looking at the signature:
(I changed the
T
forU
as we useT
inMyMutableIterator
). When we dostd::mem::replace(&mut self.slice, &mut [])
, the type ofself.slice
is&'next mut [T]
, the&mut self.slice
should be&'next mut &'next mut [T]
, thereforeU = &'next mut [T]
, shouldn't it? And in that case thestd::mem::replace
shouldn't solve anything.Maybe I'm just overthinking everything here :D Thanks.