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?
bjorn3
September 28, 2019, 3:23pm
2
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
Yandros
September 28, 2019, 10:11pm
4
If you need to access the value having lead to the predicate returning true
, you can use .position()
to get the index of the value, or .find()
to get the desired value directly.
Note: when iterating over a str
chars, you should use
.char_indices()
.find_map(|(i, c)| if predicate(c) { Some(i) } else { None })
rather than
.chars()
.position(predicate)
if intending to use the obtained number to index the str
.
From Iter<Bool> -> Bool // "any" function - #3 by Yandros
1 Like
system
Closed
December 27, 2019, 10:13pm
5
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.