Get index of element in Vec

Hello,

Given a names: Vec<String> and a name: &str, I want to get Some(index) if name is in names, otherwise None. I feel there should be some standard function to do this, but I can't find one. Did I miss it? I would write it myself like this:

fn index_for_raw(names: &[String], name: &str) -> Option<usize> {
    for i in 0 .. names.len() {
        if names[i].as_str() == name {
            return Some(i);
        }
    }
    None
}

Does something like this exist in the standard lib? Thanks!

Best, Oliver

I'd use names.iter().position(|n| n == name).

3 Likes

It was going to be part of RFC 2500, but that RFC was withdrawn.

Aside from iteration, if your slice is sorted you could use

names.binary_search_by_key(&name, String::as_str).ok()
1 Like

Awesome, thanks!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.