Logo

Programming-Idioms

History of Idiom 222 > diff from v13 to v14

Edit summary for version 14 :
Restored version 12

Version 13

2020-07-14, 19:10:14

Version 14

2020-07-18, 20:46:19

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);
Code
let opt_i = items.iter().position(|y| *y == x);


let i = match opt_i {
   Some(index) => index as i32,
   None => -1
};
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
Comments bubble
The first line is ideomatic Rust and allows you to work with an Option.

The rest is some (potentially useless/ugly) implementation of "returning -1"
Doc URL
https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.position
Doc URL
https://devdocs.io/rust/std/iter/trait.iterator#method.position
Demo URL
https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=8f986fd8a2b9fca4c465640b9051e343
Demo URL
https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=8f986fd8a2b9fca4c465640b9051e343