I'm reading Common Rust Lifetime Misconceptions to figure out how lifetime works, one of the example (posted below) really shocked me,
I can't convince myself why byte_1 and byte_2 still live well after the std::mem::drop(bytes); is executed.
From my point of view, the references which byte_1 and byte_2 hold should be invalid after the iterator bytes is dropped because the remainder array is dropped as well, the compiler should treat the drop action as an error, but in fact it pass the compiler and runs without problem...
Hope someone can give a reasonable explanation for a programmer coming from C++/C#, thanks!
struct ByteIter<'remainder> {
remainder: &'remainder [u8]
}
impl<'remainder> ByteIter<'remainder> {
fn next(&mut self) -> Option<&'remainder u8> {
if self.remainder.is_empty() {
None
} else {
let byte = &self.remainder[0];
self.remainder = &self.remainder[1..];
Some(byte)
}
}
}
fn main() {
let mut bytes = ByteIter { remainder: b"1123" };
let byte_1 = bytes.next();
let byte_2 = bytes.next();
std::mem::drop(bytes); // we can even drop the iterator now!
if byte_1 == byte_2 { // compiles
// do something
}
}
(I've been learning Rust for a month, but still confused by lots of new concepts)