-1

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

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
belkarx
  • 202
  • 4
  • 15

1 Answers1

2

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

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

Playground.

Chayim Friedman
  • 47,971
  • 5
  • 48
  • 77