Skip to content

Instantly share code, notes, and snippets.

@dmgolembiowski
Last active July 4, 2021 07:17
Show Gist options
  • Save dmgolembiowski/af8246858946efcb8fd7f33b445f6a5c to your computer and use it in GitHub Desktop.
Save dmgolembiowski/af8246858946efcb8fd7f33b445f6a5c to your computer and use it in GitHub Desktop.

I had a quick comment/question about 2.5.1's Avoid Managing An Index Variable:

It's common [in] many languages to loop through things by using a temporary variable that's incremented... A Rust version of that pattern would be this snippet:

let collection = [1, 2, 3, 4, 5];
for i in 0..collection.len() {
  let item = collection[i];
  // ...
}

This is legal Rust. It's also essential in cases where iterating directly over collection (for item in collection) is impossible. However, it is generally discouraged. The manual approach introduces two problems:

  • Performance Indexing values with collection[index] syntax incurs runtime costs for bounds checking. That is, Rust will check [whether] that index currently exists within collection as valid data. Those checks are not necessary when iterating directly over collection. The compiler can use compile-time analysis to prove that illegal access is impossible.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment