Skip to content

Commit 9c2a5ed

Browse files
authored
Unrolled build for rust-lang#122015
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 7d3702e + 6600c97 commit 9c2a5ed

File tree

1 file changed

+18
-1
lines changed
  • compiler/rustc_index/src

1 file changed

+18
-1
lines changed

Diff for: compiler/rustc_index/src/vec.rs

+18-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,24 @@ 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`,
1835
/// you almost certainly want to use a [`newtype_index!`]-generated type instead.

0 commit comments

Comments
 (0)