Poperton
Poperton

Reputation: 2236

How to safely subslice a rust slice?

On Rust you can subslice a slice/vector/etc

fn main() {
    let a = vec![0; 6];
    let b = &a[0..2];
    println!("{:?}", b);
}

however this panics if the range for which you're slicing is too big.

Is there a safe way to subslice and get an option if the subslice succeeded or not?

Upvotes: 4

Views: 1786

Answers (1)

Chayim Friedman
Chayim Friedman

Reputation: 71370

Use get():

fn main() {
    let a = vec![0; 6];
    let b = a.get(0..2);
    println!("{:?}", b);
}

Upvotes: 7

Related Questions