Catch panic on vec drain

Viewed 114

What is the best way to catch this panic?

fn main() {
    let mut v = vec![1, 2, 3, 4, 5];
    let u: Vec<_> = v.drain(.. 8).collect();
}

I know that I could do something like this

fn main() {
    let mut v = vec![1, 2, 3, 4, 5];
    if v.len() < 8 {
        // error here...
    }
    let u: Vec<_> = v.drain(.. 8).collect();
}

Is there a better way to do this? I'd like to catch "all" errors, not just if the index is greater than the length. I couldn't find anything in the documentation beyond.

Panics if the starting point is greater than the end point or if the end point is greater than the length of the vector.

1 Answers

You could use slice::get():

fn main() {
    let mut v = vec![1, 2, 3, 4, 5];
    let range = 8..2;
    if v.get(range.clone()).is_some() {
      let u: Vec<_> = v.drain(range).collect();
    }
    else {
        // bad
    }
}
Related