logoalt Hacker News

hingler36 • today at 6:37 AM • 3 replies • view on HN

I've always felt that parts of the Rust standard library to be weirdly un-rusty. Like indexing a vector panicking instead of returning a Some(T) in case the index is out of bounds. It's easy to avoid if you put the effort in of course, but it did always feel weird that one of the first data structures you learn has this behavior right out of the gate.


Replies

Chai-T-Rex • today at 6:49 AM

That's not really a memory safety bug, due to the fact that it panics rather than doing something unsafe.

The `variable[i]` notation is intended to function like in other languages, where it returns an unwrapped value. It would be ugly, noisy, unergonomic, and annoying to have to properly handle `Some` (like in `variable[i].unwrap()`) every single time you ever used it. Imagine doing `c[i].unwrap()[j].unwrap() += a[i].unwrap()[k].unwrap() * b[k].unwrap()[j].unwrap();`.

If you really want the result to be wrapped in `Some`, you can use `variable.get(i)`.

➕ show 2 replies
suresk • today at 6:54 AM

I think it is a reasonable tradeoff, especially since `get(i)` is available to do what you want. An array index oob error is usually a logic issue, not some recoverable error, and in a lot of cases you're doing it where it is impossible to be wrong, so it is a lot of error-checking (and giving up things like x[0] += 1) to have the Index trait return an Option instead of a direct reference.

saagarjha • today at 7:18 AM

> Like indexing a vector panicking instead of returning a Some(T) in case the index is out of bounds.

If you are doing this then you've made a mistake in your code. Rust is consistent in catching these early.

➕ show 1 reply