Logo

Programming-Idioms

History of Idiom 222 > diff from v14 to v15

Edit summary for version 15 by programming-idioms.org:
New Rust implementation by user [programming-idioms.org]

Version 14

2020-07-18, 20:46:19

Version 15

2020-07-18, 20:49:05

Idiom #222 Find first index of an element in list

Set i to the first index in list items at which the element x can be found, or -1 if items does not contain x.

Idiom #222 Find first index of an element in list

Set i to the first index in list items at which the element x can be found, or -1 if items does not contain x.

Extra Keywords
position
Extra Keywords
position
Code
let i = items.iter().position(|y| *y == x).map_or(-1, |n| n as i32);
Comments bubble
Rust uses the usize type to index lists, but it can't be negative. We need to manually convert it to an i32 to be able to return -1
Doc URL
https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.position