Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to slice to a particular element in a Vec (rust)

What is the best way to slice a Vec of u32s (or any generic type) to the first occurrence of a particular number?

Naive, un-rusty 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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

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

Playground.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading