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 https://doc.rust-lang.org/std/vec/struct.Vec.html 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)

https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.position

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

v.iter().find(f)

https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.find

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

1 Like