3 ms·
Indexing into an array or vec will always be checked in safe Rust, so if an overflow gives you a bad index you'll just get a panic (or an Option::None if you de
by brundolf 4y ago
Indexing into an array or vec will always be checked in safe Rust, so if an overflow gives you a bad index you'll just get a panic (or an Option::None if you decided to access it that way); never a safety issue
- throwaway81523 4y agoIndexes are only checked for being outside the array, not for being wrong. Getting a[3] when you wanted a[5] is a bug, potentially a serious or dangerous one. SPARK Ada goes to great lengths to statically verify that there are no int overflows in the code that it checks, and Ada itself specifies trapping overflow, though as an "optimization", the overflow check is often disabled. OCaml also checks overflow for its machine int type. GHC doesn't, and that seems like a mistake.
- brundolf 4y ago"Safety" means a specific thing here, and whatever bugs might happen with this, they do not make the code "unsafe" It also helps that, in practice, when writing idiomatic Rust you'll almost always be accessing array/vec members using an iterator. Direct indexing is uncommon, which means indexing bugs specifically are very uncommon. Of course that's not the only bug that overflows can cause, but it's a big one. Not every bug can be prevented by the language (at compile time or runtime). You have to make some choices about which things are just in the programmer's hands, and I think Rust has struck a reasonable balance. Especially since the user can always choose differently in this case, and just compile their code with `overflow-checks = true`