How to malloc an array in heap like C?

Directly, to guarantee it, is to use .get_unchecked(i) instead of [i].

Indirectly, is to use iterators. Iterators typically avoid unnecessary bounds checks.

for item in vec {}

for (index, item) in vec.iter().enumerate() {}

etc.

There's also a trick that helps prove to LLVM that a slice is large enough, so that it can optimize checks out. You can check whether LLVM can figure it out by testing code on https://rust.godbolt.org

let has_known_length = &vec[0..len];
for i in 0..len {
    has_known_length[i]; // probably not bounds checked anymore, if llvm can see both 0..len
}

but iterators are usually the best solution - safe and fast by default.

6 Likes