Hacker News new | past | comments | ask | show | jobs | submit login

I think the primary argument for Rust advocates here is that what you describe is only possible by using explicitly "unsafe" code (i.e. code using the "unsafe" block that is required).

The weakness of this argument is exposed in your comment also: in libraries "unsafe" is often hidden behind an abstraction. To take a simple example, consider the standard Rust Vec: plenty of "unsafe" code resides in this object, but you'll rarely if ever see "unsafe" wrap typical vector operations ("unsafe { myvec[0] }"). Partial mitigation is that this does reduce the surface area where one might have to look if odd behaviors start to appear in a Rust program.

Overall it's still a net benefit.




> ("unsafe { myvec[0] }")

Part of the point in my post is that this does not remove the bounds check. This unsafe block does nothing.

This actually might be a better example than the one I picked...


And just as in the OP, the compiler makes it clear that this unsafe block does nothing:

    warning: unnecessary `unsafe` block
     --> src/main.rs:4:3
      |
    4 |   unsafe { myvec[0]; }
      |   ^^^^^^ unnecessary `unsafe` block
      |


I might be in the minority here (and I don't do game development, which is the topic of this thread), but I tend to start by using `vec.get(i)` (which returns an option) and then only switch to the index notation if I end up checking the length immediately beforehand and want to do an early return or something to avoid extra indentation in the code where I use the accessed element.


I think modern C++ compilers are smart enough to eliminate the bounds check if they can prove that it never fails.


Yup, Rust will too.


I mainly do it this way to reduce the chance of my code panicking, not specifically for any performance reasons.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: