2 ms·
Rust provides two methods for array indexing. `my_array[i]` which panics if `i` is out of bounds, and `my_array.get(i)` which returns `None` if `i` is out of bo
by gamegoblin 9y ago
Rust provides two methods for array indexing. `my_array[i]` which panics if `i` is out of bounds, and `my_array.get(i)` which returns `None` if `i` is out of bounds. The same thing applies to `HashMap` etc.
For the vast majority of cases, it is an non-recoverable logic error to try to access an out-of-bounds elements, so panicking makes sense for the more common, more terse `my_array[i]` syntax.
For me, recoverability dictates whether or not to return `Option<T>` or `T-but-maybe-panic`. If a caller can reasonably recover (and in fact expects to get `None` some of the time!), then `Option<T>` is the right choice. If it is obviously an irrecoverable logic error, then maybe panicking is the right choice.
- foldr 9y agoYes, I'm aware of how Rust handles array indexing. I was just noting that autounwrapping wouldn't be any less safe than the existing behavior for array indexing using [].