Array out of bound error handling

consider that i have 3 element in my array of size 3 i try to add 4th element which cause error array out of bount
how to handel this error using
match{
ok=>
err=>
}
or
idg let ok(){}

You can use get_mut:

match array.get_mut(3) {
    Some(x) => { *x = 0; }
    None => { println!("oops, out of bounds"); }
}
2 Likes

This is quite a difficult question to answer, but here goes....

If you're using an array of the form

[2, 3, 4]

then it is a fixed-length array and trying to assign out-of-bounds will not compile. There is no push method to add a value at the end.

If you're using a slice (that's a view of some contiguous data, like a stack array or a heap-allocated vector), and you try to access data out-of-bounds, your program will panic. There are the methods get and get_mut that return Options instead (see @mbrubeck's answer).

2 Likes

is any features like try catch Available in rust

Not really, at least not in the way you mean.

The best way we can help you is if you share what you are trying to accomplish in pseudo-code or the language of your choice :wink:

1 Like

Error handling in rust is done with the Optional Result enums and the ? operator which will return early if the result cannot unwrap to Some or an Okay-ish type.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.