Lifetime of ref from .iter()

let v: &'a Vec<T> = todo!();
for t in v.iter() {

We know that t: &T question is: is the lifetime t: &'a T, or is it something shorter (i..e the lifetime of one iteration of the loop) ? If it is the latter, is there anyway to force t: &'a T ?

[running into weird runtime error]

EDIT: lifetime error, not runtime error

Iterators borrow from the collection, so the items returned outlive the iterator.

The scope of the lifetime is established when the collection is borrowed. In your case it's borrowed when you call iter(). If Rust is not inferring the lifetime you want, try first explicitly converting &Vec to &[T].


It can be &'a T it can also be shorter, but for shared references like this it doesn’t really ever need to be shorter, so you can probably best think of it as just always being &'a T.

Runtime behavior is not actually ever affected by what the “actual lifetime” so-to-speak of a reference is. So you might be asking the wrong question here, or rather, a question that has nothing to do with the runtime error you ran into.


Lifetimes don't exist at runtime, and aren't prescriptive -- they're bounds that must be met (or perhaps more accurately, not violated). If the compiler can prove there are no violations, it compiles.

You can use a variable to make sure it's alive at some point, e.g. drop(variable).

Beyond that, there's not much context about what sort of problem you're hitting.

  1. Terrible typo on my part, should say 'lifetime'

  2. Problem (unrelated to post) solved (for unrelated reason).

Sorry for confusing question.
Thanks to everyone for help.


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.