Hi all,
I'm creating a simple game of tic-tac-toe and would like help understanding arrays.
I was under the assumption that Rust would not compile if your code is capable of panicking.
However, in the below code, I index a 2D array in try_update_cell() in an unsafe manner and I am capable of compiling this with zero errors or warnings, in release mode.
Could someone kindly clarify if this is intentional behaviour, and why?
Am I operating on a false assumption?
The safety Rust provides (around array access), and that you might have heard about hence are wondering, are those panics. It panics because it is checking for out-of-bounds access, whereas less safe languages donโt, creating genuinely unsafe situations (which might crashโฆ or notโฆ).
Proving out of bounds access statically is not generally possible. At runtime, arrays (Vec) may grow and shrink dynamically. No language can foresee the future like that.
Rust also has arrays (slices) of statically known length though, where static checks for out of bound access are possible in limited fashion.
Adding some theoretical background to that: In fact it can be shown to be impossible by trivial equivalence with the halting problem: you could make the length of a vector depend on the output of an arbitrary computation. Or you make your program access an index based on arbitrary computation.
And then separately there is of course also IO: Why not just ask the user to enter the index on standard input?
Do not be disappointed. Be happy your program panics when your code runs off the end of an array. Rather than continuing with some erroneous result or crashing mysteriously: Which can waste a lot of time in debugging. Which can cause you to get calls in the middle of the night to fix some rarely occurring problem that just happened to occur.
As noted above, it is not even possible for the compiler to know what weird situations your program will run into when run. So the safety checks necessarily have to be inserted into the code to cause panics at run time.
Also as noted above one can use iterators and such to avoid array indexing in the first place. Which means the compiler builds the code for you and run-time checks can be avoided.