Nurbol Alpysbayev
Nurbol Alpysbayev

Reputation: 21851

How to find a value in a vector and return its index, in a functional way?

I can't find in the docs an iterator method that will allow to write code equivalent to this:

let v = vec![1,2,3];
let key_of_two = v.iter().find_key(|x| x == 2);
assert_eq!(key_of_two, 1)

There's only find method, but how to return the index, instead of the element?

Upvotes: 1

Views: 2917

Answers (1)

edwardw
edwardw

Reputation: 13942

Fortunately there is Iterator::position:

let v = vec![1,2,3];
let key_of_two = v.iter().position(|&x| x == 2);
assert_eq!(key_of_two, Some(1));

Upvotes: 4

Related Questions