Pictured: Rustc
Conversation
By the way, something I don't understand.
So it lets me do this.
"array" is unused, it gives me an unused var warning.
but… it *can't* be used?!
I didn't initialize it, you can't read an uninitialized var, and it isn't mut so I can't write into it.
Why does it LET me define it?
3
6
Ohh
read image description
ALT
3
7
This statement in the reference for "slice" is what I want, but also it is bad. Are there (safe) steps I can take to reliably ensure bounds-checking for a particular use of a slice is removed before runtime? Are the rules for this documented somewhere (such as the rustc manual)?
6
4
Like what I'm looking for is some way to type or decorate a site such that I'm asserting "I think I followed the rules to get a no-boundcheck optimization here, and if I messed up, I want the compiler to tell me so"
4
8
Several people replying "use iterators". Good approach, but here's a complication:
I often find myself in a situation where I have 2 arrays, incidentally of the same length.
int a:[T], b:[T];
I want to iterate over "both at once". For example produce a c such c[i] = a[i] + b[i]
1
7
Using the iterator syntax (which remember, I want to use because I want the language-level guarantee I'm avoiding bounds checks), is there a way to iterate over 2 arrays (or iterate up to end of shorter array)? In C I'd do this by iterating over key range and random indexing.
7
5
Replying to
Iterators are almost entirely library feature. The language provides some syntactic sugar via `for` loops.
The standard library's slice iterator has start and end pointers with the core iterator next method implemented as advancing by an element and comparing to the end pointer.
1
1
Replying to
If it happens to be the case that the standard library iterators will always follow the code path that removes the bounds checks at individual index sites, and this is a strong and universally understood social contract, that's "as good as" a lang guarantee for now i think
4
3
conveniently this is true of _all_ iterators, not just those in the standard library. while it's /possible/ to make an iterator that checks too much or deliberately escapes bounds, doing so requires active intention and leaves obvious signs in the source code
1
Yeah, so there aren't bounds checks in unoptimized code either. It does heavily depend on very basic optimization to inline layers of function calls and get rid of the trivial cruft. It's only the more complex adaptors like filter which really depend on advanced optimizations.
The compiler needs to deal with the whole chain of many redundant checks for the end of iteration, etc. The compiler isn't expected to do anything particularly complex though. The approach would perform very well even with a really stupid compiler aside from the complex adaptors.


