Search code examples
rustvector

How to slice to a particular element in a Vec?


What is the best way to slice a Vec to the first occurrence of a particular element?

A naive method demonstrating what I want to do:

fn main() {
    let v = vec![1, 2, 3, 4, 5, 6];
    let to_num = 5;
    let mut idx = 0;
    for x in &v {
        if x != &to_num {
            idx += 1
        } else {
            break;
        }
    }
    let slice = &v[..idx];
    println!("{:?}", slice); //prints [1, 2, 3, 4]
}

^ on the Rust playground


Solution

  • You can use <[T]>::split():

    let slice = v.split(|x| *x == to_num).next().unwrap();
    

    Playground.