Logo

Programming-Idioms

History of Idiom 222 > diff from v21 to v22

Edit summary for version 22 by programming-idioms.org:
[Rust] +DemoURL

Version 21

2021-01-29, 18:19:49

Version 22

2021-03-26, 18:36:51

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.

Variables
i,x,items
Variables
i,x,items
Extra Keywords
position
Extra Keywords
position
Code
let i = items.iter().position(|y| *y == x).map_or(-1, |n| n as i32);
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
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
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=744d65fe27132971ecd70c8398b8639b