Logo

Programming-Idioms

History of Idiom 222 > diff from v11 to v12

Edit summary for version 12 :
New Rust implementation by user [strom-und-spiele]

Version 11

2020-04-29, 00:34:41

Version 12

2020-06-04, 11:25:20

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


let i = match opt_i {
   Some(index) => index as i32,
   None => -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://devdocs.io/rust/std/iter/trait.iterator#method.position
Demo URL
https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=8f986fd8a2b9fca4c465640b9051e343