How to handle an index out of bounds error?

Viewed 768

What is the idiomatic way to handle this to avoid a runtime error:

let address = match x[1].parse::<String>() {
    Ok(a) => Some(a),
    Err(_) => None,
};

Where x[1] could panic with an index out of bounds error?

1 Answers

You could use get See: Slice documentation.

let address: Option<String> = x.get(1).and_then(|v| {
    v.parse().ok()
});
Related