Logo

Programming-Idioms

History of Idiom 222 > diff from v12 to v13

Edit summary for version 13 :
[Rust] While the task is a little strange, it's perfectly possible in Rust, and this example demonstrates usage of Option

Version 12

2020-06-04, 11:25:20

Version 13

2020-07-14, 19:10:14

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
};
Code
let i = items.iter().position(|y| *y == x).map_or(-1, |n| n as i32);
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"
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://devdocs.io/rust/std/iter/trait.iterator#method.position
Doc URL
https://doc.rust-lang.org/std/iter/trait.Iterator.html#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