Obviously, if you have to check an index length you're going to be doing a branch. However, because the index checks are intrinsic to the Rust compiler, it can remove them when it proves the code is safe. So, for instance, an iteration loop over an array won't have any index checks in the generated machine code.
- being intrinsic is absolutely not required for the checks to be removed. Bounds checks are just a normal branch with a fairly straight-forward condition, and the always-true nature of those conditions is inferred in the same way for both the built-in indexing and non-built-in indexing. This is true in languages other than Rust.
An iterator is designed to just not do any indexing at all (neither using the built-in [] operator or one of the functions that implements manual bounds checks), because it instead just manually (unsafely) walks a pointer along the array.
> An iterator is designed to just not do any indexing at all (neither using the built-in [] operator or one of the functions that implements manual bounds checks), because it instead just manually (unsafely) walks a pointer along the array.
It obviously still has to bound-check that it's not about to walk right out of the array. If you want to call this something other than a "bound-check", I think that's being overly pedantic.
Yes, it checks that it's reached the end of the array as part of the loop, in the same place that `for (int i = 0; i < n; i++)` checks whether it's reached the end of the loop. I think this is different to the indexing bounds checks we've been discussing since the whole process is more controlled (compare and increment a pointer), rather than taking an arbitrary integer.
But yes, strictly speaking you're right, an iterator does do check when it's reached the end of the array, it just doesn't do any indexing nor does it use the indexing checks built into the compiler (which is what you implied the iterators benefit from).
> because the index checks are intrinsic to the Rust compiler
This is false. The index checks are written in Rust code as an impl of the Index trait on [T].
The checks being removed have nothing to do with this -- LLVM can prove that certain checks are unnecessary. C does the same, if you used a library that provided checked indexing.
What's different is that in Rust indexing is overall used much less often, because iterators are the dominant pattern, which completely sidesteps this pattern.