The problem is that the Peekable
iterator lives to the end of the function, but it holds a reference to the vector returned by get_m
, which only lasts as long as the statement containing that call.
There are actually a lot of things going on here, so let's take it step by step:
get_m
allocates and returns a vector, of type Vec<i8>
.
- We make the call
.iter()
. Surprisingly, Vec<i8>
has no iter
method, nor does it implement any trait that has one. So there are three sub-steps here:
- Any method call checks whether its
self
value implements the Deref
trait, and applies it if necessary. Vec<i8>
does implement Deref
, so we implicitly call its deref
method. However, deref
takes its self
argument by reference, which means that get_m()
is now an rvalue appearing in an lvalue context. In this situation, Rust creates a temporary to hold the value, and passes a reference to that. (Keep an eye on this temporary!)
- We call
deref
, yielding a slice of type &[i8]
borrowing the vector's elements.
- This slice implements the
SliceExt
trait, which does have an iter
method. Finally! This iter
also takes its self
argument by reference, and returns a std::slice::Iter
holding a reference to the slice.
- We make the call
.peekable()
. As before, std::slice::Iter
has no peekable
method, but it does implement Iterator
; IteratorExt
is implemented for every Iterator
; and IteratorExt
does have a peekable
method. This takes its self
by value, so the Iter
is consumed, and we get a std::iter::Peekable
back in return, again holding a reference to the slice.
- This
Peekable
is then bound to the variable vals
, which lives to the end of the function.
- The temporary holding the original
Vec<i8>
, to whose elements the Peekable
refers, now dies. Oops. This is the borrowed value not living long enough.
But the temporary dies there only because that's the rule for temporaries. If we give it a name, then it lasts as long as its name is in scope:
let vec = get_m();
let mut peekable = vec.iter().peekable();
println!("Saw a {:?}", vals.peek());
I think that's the story. What still confuses me, though, is why that temporary doesn't live longer, even without a name. The Rust reference says, "A temporary's lifetime equals the largest lifetime of any reference that points to it." But that's clearly not the case here.