Skip to content

Improve documentation and error message for Vec type on erroneous indexing #36645

Closed
@andradei

Description

@andradei

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
  • Vec implements:
    • 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 usize for 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

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 of usize is implied in the doc examples and is explicitly stated in the part that shows what traits Vec implements - both hard for beginners to find and comprehend

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsC-enhancementCategory: An issue proposing an enhancement or a PR with one.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions