Skip to content

Commit ebd3a4f

Browse files
authored
Rollup merge of rust-lang#122015 - dev-ardi:master, r=nnethercote
Add better explanation for `rustc_index::IndexVec` I feel like I didn't do a great job explaining what this does in rust-lang#119800, so this PR tries to give an example of why and how you would use it. Addresses rust-lang#93792.
2 parents 85adf44 + beb45df commit ebd3a4f

File tree

1 file changed

+19
-2
lines changed
  • compiler/rustc_index/src

1 file changed

+19
-2
lines changed

compiler/rustc_index/src/vec.rs

+19-2
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,27 @@ use std::vec;
1212
use crate::{Idx, IndexSlice};
1313

1414
/// An owned contiguous collection of `T`s, indexed by `I` rather than by `usize`.
15-
/// Its purpose is to avoid mixing indexes.
15+
///
16+
/// ## Why use this instead of a `Vec`?
17+
///
18+
/// An `IndexVec` allows element access only via a specific associated index type, meaning that
19+
/// trying to use the wrong index type (possibly accessing an invalid element) will fail at
20+
/// compile time.
21+
///
22+
/// It also documents what the index is indexing: in a `HashMap<usize, Something>` it's not
23+
/// immediately clear what the `usize` means, while a `HashMap<FieldIdx, Something>` makes it obvious.
24+
///
25+
/// ```compile_fail
26+
/// use rustc_index::{Idx, IndexVec};
27+
///
28+
/// fn f<I1: Idx, I2: Idx>(vec1: IndexVec<I1, u8>, idx1: I1, idx2: I2) {
29+
/// &vec1[idx1]; // Ok
30+
/// &vec1[idx2]; // Compile error!
31+
/// }
32+
/// ```
1633
///
1734
/// While it's possible to use `u32` or `usize` directly for `I`,
18-
/// you almost certainly want to use a [`newtype_index!`]-generated type instead.
35+
/// you almost certainly want to use a [`newtype_index!`] generated type instead.
1936
///
2037
/// This allows to index the IndexVec with the new index type.
2138
///

0 commit comments

Comments
 (0)