4 ms·
> 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.
by epage 8y 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 `[]`.
- Shoop 8y agoIt'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.
- masklinn 8y agoExcept Rust's [] behaves like C++'s at (checks and aborts). C++'s [] is called `get_unchecked`.
- int_19h 8y agoC++ 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.
- masklinn 8y ago> 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 [].
- pjmlp 8y agoIf you do that, you will be invoking nasal daemons, as at() is required by ISO C++ to throw.
- jcelerier 8y agothankfully, ISO C++ is a language that no one actually programs in, everyone use `MSVC C++`, `g++ 8.2.1 -fwhatever`, etc
- pjmlp 8y agoOn 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.
- Sharlin 8y agoIt'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).