Hacker News new | ask | show | jobs
by epage 2674 days ago
> 1. I find it odd that some things like slice reads can still panic by default. Yes, I can use `foo.get(1)` to avoid panics, but still - it's a bit odd to me.

I wonder if this is similar to C++'s `[]` vs `at`. `at` does implicit bounds checking but, as an optimization, if you are already doing an explicit bounds check, you can elide the implicit check via `[]`.

3 comments

It's more about ergonomics. With `get` you get an `Option` which allows you to handle the out-of-bounds situation, but is unnecessarily noisy when you know that the index must be valid unless the program is buggy (and in that case you most likely want to abort anyway).
It's somewhat similar, except C++'s [] leads to memory unsafety whereas Rust's [] on slices has bounds checks and will abort the program on failure. Your program will crash but it won't be an exploitable bug (except for a DOS). .get(), meanwhile, returns an Option so that code written using it can recover from OOB accesses.
Except Rust's [] behaves like C++'s at (checks and aborts). C++'s [] is called `get_unchecked`.
C++ at() doesn't check and abort, it checks and throws a specific documented exception that you can catch. So it is, in fact, closer to get(), just using a very inefficient way of reporting.
> C++ at() doesn't check and abort, it checks and throws a specific documented exception that you can catch. So it is, in fact, closer to get(), just using a very inefficient way of reporting.

You can catch a panic, and you can compile C++ with -fno-exception. at() is not closer to get() than to [].

If you do that, you will be invoking nasal daemons, as at() is required by ISO C++ to throw.
thankfully, ISO C++ is a language that no one actually programs in, everyone use `MSVC C++`, `g++ 8.2.1 -fwhatever`, etc
On real world where code portability actually matters, many do program against ISO C++, and have to deal with workarounds for lack of compliance.

Not doing so means ending up with situations like the Linux kernel, Windows or console games, which might be ok, when code portability doesn't matter to start with.