I frequently wish there was a way to combine bounds checking with indexing. What if you could index slices with slice?[index], which would check the bounds for you and return null if the index is out of range, instead of panicking/causing UB?
const foo = slice?[index];
// would be equivalent to
const foo = if (index >= 0 and index < slice.len) slice[index] else null;
There are lots of places in the stdlib that would benefit from this too, for example:
I didn’t think this is a bad idea, actually. Maybe the syntax could be worked on, (maybe reusing try?) but I think it would definitely be useful for more explicit runtime bounds-checking behavior.
I concur, I think what most people may agree upon is (conditionally) enabling bounds checking in debug builds, and optimize them away in release builds.
Writing a function which gets an element with bounds checking is not terribly hard, if you really really want it:
Assuming index is usize there is no need for index >= 0 and :
const foo = if (index < slice.len) slice[index] else null;
I think this would encourage re-checking values, that are already known to be null, repeatedly, just because the operator makes it convenient.
Instead I would prefer early-exit (instead of chaining null through multiple later statements):