Vec : index of first elem satisfying property

I have:

T: Type;
v: Vec<T>;
f: Fn (&T) -> bool;

I want to get a Option<usize> of the first index i s.t. f(v[i]) returns true.

I'm looking at Vec in std::vec - Rust and there appears to be no function that returns type Option<usize>

Question: is there a builtin for solving this?

Yes:

v.iter().position(f)

If you want to get a reference to the element itself, you can use:

v.iter().find(f)
4 Likes

You're looking for an immutable function which traverses the items in the Vec, so you should first look in the slice documentation (Because it's immutable) and then in the Iterator documentation.

my_iterator.find(f)

Should Work

my_iterator.position(f)
my_iterator.rposition(f)

Could work too.

2 Likes

From Iter<Bool> -> Bool // "any" function - #3 by Yandros

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.