about summary refs log tree commit diff
path: root/compiler/rustc_index/src/vec.rs
diff options
context:
space:
mode:
authororion GONZALEZ (contractor) <orion.gonzalez@amadeus.com>2024-03-06 16:54:42 +0100
committerorion GONZALEZ (contractor) <orion.gonzalez@amadeus.com>2024-03-06 16:54:42 +0100
commit6600c972e6c74f8a528aecbeaf0a2937ceed8984 (patch)
tree3ac206f06570aefd691d1fd1044101feda77a3ea /compiler/rustc_index/src/vec.rs
parent53ed660d47feb01055483fe81b628d5ef9705dbd (diff)
downloadrust-6600c972e6c74f8a528aecbeaf0a2937ceed8984.tar.gz
rust-6600c972e6c74f8a528aecbeaf0a2937ceed8984.zip
doc: Add better explanation
Diffstat (limited to 'compiler/rustc_index/src/vec.rs')
-rw-r--r--compiler/rustc_index/src/vec.rs19
1 files changed, 18 insertions, 1 deletions
diff --git a/compiler/rustc_index/src/vec.rs b/compiler/rustc_index/src/vec.rs
index d876174e620..88298150a79 100644
--- a/compiler/rustc_index/src/vec.rs
+++ b/compiler/rustc_index/src/vec.rs
@@ -12,7 +12,24 @@ use std::vec;
 use crate::{Idx, IndexSlice};
 
 /// An owned contiguous collection of `T`s, indexed by `I` rather than by `usize`.
-/// Its purpose is to avoid mixing indexes.
+///
+/// ## Why use this instead of a `Vec`?
+///
+/// An `IndexVec` allows element access only via a specific associated index type, meaning that
+/// trying to use the wrong index type (possibly accessing an invalid element) will fail at
+/// compile time.
+///
+/// It also documents what the index is indexing: in a `HashMap<usize, Something>` it's not
+/// immediately clear what the `usize` means, while a `HashMap<FieldIdx, Something>` makes it obvious.
+///
+/// ```compile_fail
+/// use rustc_index::{Idx, IndexVec};
+///
+/// fn f<I1: Idx, I2: Idx>(vec1: IndexVec<I1, u8>, idx1: I1, idx2: I2) {
+///   &vec1[idx1]; // Ok
+///   &vec1[idx2]; // Compile error!
+/// }
+/// ```
 ///
 /// While it's possible to use `u32` or `usize` directly for `I`,
 /// you almost certainly want to use a [`newtype_index!`]-generated type instead.