3 ms·
> (Have to double space due to lack of formatting capabilities here.) Indent by four spaces to get a <pre> tag: let mut v = vec![1i32, 2, 3, 4, 5]; le
by haberman 12y ago
> (Have to double space due to lack of formatting capabilities here.)
Indent by four spaces to get a <pre> tag:
let mut v = vec![1i32, 2, 3, 4, 5];
let vlen = v.len()
for i in range(0, vlen) {
let x = &mut v[i];
// do some work with x
}
> This seems to be a forgotten technology.
Given what I know about Rust, I strongly suspect that there is a way in Rust to iterate over a vector with only a single hoisted bounds-check. Hopefully other Rust people can chime in on what this is.
- veddan 12y agoIn most cases, you use iterators rather than indexing for x in v.iter_mut() { // do some work with x } or if you need the index for (i, x) in v.iter_mut().enumerate() { // do some work with x and i } similar to Python's enumerate(). These loops never need to do any bounds-checking, even when compiling without optimization. In this example the iteration count is a small compile-time constant (5), and the loop body is small, so when compiling with optimizations the loop will be unrolled.
- masklinn 12y ago> I strongly suspect that there is a way in Rust to iterate over a vector with only a single hoisted bounds-check. Hopefully other Rust people can chime in on what this is. Iterators.