-
Notifications
You must be signed in to change notification settings - Fork 14k
Closed
Labels
A-diagnosticsArea: Messages for errors, warnings, and lintsArea: Messages for errors, warnings, and lintsC-enhancementCategory: An issue proposing an enhancement or a PR with one.Category: An issue proposing an enhancement or a PR with one.
Description
Note Similar issue to #31062
Documentation problem
The error for trying to index Vec with the wrong type isn't clear. A couple of examples:
- Example 1
vec![0][0i32]The error for this is:
error: the trait bound `std::vec::Vec<_>: std::ops::Index<i32>` is not satisfied [--explain E0277]
- Example 2
fn main() {
let n = 5u32; // This value could come from a struct member or function call.
let vec: Vec<i32> = vec![1, 2, 3, 4, 5];
for i in 0..n {
println!("{}", vec[i])
}
}The error:
error: the trait bound `std::vec::Vec<i32>: std::ops::Index<u32>` is not satisfied [--explain E0277]
The error hints that Vec implements the Index trait, but it doesn't say that it implements it for usize specifically. Instead, it says that it doesn't implement Index for the type you tried to index with.
This is very confusing for beginners, finding the answer involves a knowledge of:
- Traits and how they work
- Rust's type behavior (due to its powerful type system) many times comes from implementing traits
- Indexing on a type is possible via a trait called
Index Vecimplements:impl<T> Index<usize> for Vec<T>impl<T> IndexMut<usize> for Vec<T>impl<T> Index<Range<usize>> for Vec<T>- And a bunch or others, all using
usizefor indexing
While it makes the most sense that usize is used, it might not be obvious at first (specially for beginners like me). Trying to index with any other numerical primitive (i8, u8, etc.) will result in the error shown above.
Possible solutions
- Use the same or similar solution to provide on_unimplemented hint for ops::Index #31062
- Make the error state that
Vecimplements indexing forusizeonly. Maybe something like:
error: the trait bound `std::vec::Vec<i32>: std::ops::Index<u32>` is not satisfied.
std::vec::Vec<T> implements std:ops:Index<usize>, implements std:ops:Index<Range<usize>>, etc...
[--explain E0277]
- Add that info on
rustc --explain E0277 - Add this information in the documentation for
Vec, the use ofusizeis implied in the doc examples and is explicitly stated in the part that shows what traitsVecimplements - both hard for beginners to find and comprehend
Idyllei, Ixrec and kmeisthax
Metadata
Metadata
Assignees
Labels
A-diagnosticsArea: Messages for errors, warnings, and lintsArea: Messages for errors, warnings, and lintsC-enhancementCategory: An issue proposing an enhancement or a PR with one.Category: An issue proposing an enhancement or a PR with one.