Builtin Trait for "this object has .iter()"?

This is not difficult to write, but I am wondering if there is a standard trait for

"We can call .iter() on this object."

For example, I would want this to cover Vec, HashSet, im::Vec, im::HashSet ...

IntoIterator

2 Likes

Note that IntoIterator consumes self, but it’s implemented for things like &Vec as well. If you’re writing generic code that needs to iterate multiple times over the same items, you’ll need to include a Clone bound somewhere.

This will let you do the equivalent of Vec::iter, HashSet::iter, etc.

fn foo<V>(v: &V) where for<'a> &'a V: IntoIterator {
    let mut iter = v.into_iter();
}

This works because, by convention, vec.iter() is equivalent to (&vec).into_iter(), and so on.

6 Likes

This may make more sense as a separate thread, but can you explain why this works?

fn foo<V>(v: &V) where for<'a> &'a V: IntoIterator {
    let mut iter = v.into_iter();
}

fn bar<'b>(x: Vec<&'b u32>) {
    foo(&x);
}

There are some lifetimes for which &'a Vec<&'b u32> is not a valid type, namely if 'a is longer than 'b. As such, I expected the universal quantifier for<'a> &'a V to block the implementation-- In similar situations (I can't remember which at the moment), I've gotten errors like V may not live long enough, but this one compiles without issue.

1 Like

I don’t actually think HRTB is needed here since the lifetime of the reference is known. This also works.

fn foo<'a, V>(v: &'a V) where &'a V: IntoIterator {
    let mut iter = v.into_iter();
}

With respect to why the HRTB version works, I think the check whether the lifetimes are compatible is dependent on the functions defined in the program rather than a hypothetical function with incompatible lifetimes. Otherwise it would be impossible to use HRTB with a generic since a generic could be any lifetime. And in this case since the outer reference is defined in the function and the inner reference lifetime is defined outside the function, the outer lifetime must be shorter than the inner one. At least that's my understanding.

2 Likes