rust-lang / rust-lang/rust

Potential documentation gap in `impl Index<Range<usize>> for [T]`

Open
#121,568 3 comments 0 reactions 1 assignee View on GitHub

@JaniM is already working on this.

Since Mar 31, 2024.

A-docs T-libs
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

Location

Index::index

Summary

In Rust, if you attempt to index a slice or array with a "backwards" Range<usize> , the program panics:

let arr = [0,1,2,3,4,5,6];
let slice = &arr[4..1]; // panic: slice index starts at 4 but ends at 1 

This behavior is unsurprising, but not obvious: a reasonable alternative behavior would be to just return the empty slice &[]. This is what python does.

The documentation for Index::index states that the indexing operation "May panic if the index is out of bounds", but doesn't define what it means to be "out of bounds". I'd argue that in this example, the Range 4..1 is actually not out-of-bounds for an array of size 7 because both 4 and 1 are less than 7 and therefore, by the letter of the documentation, the panic behavior here is wrong and returning the empty slice &[] is a more reasonable behavior to expect than panicking.

I feel like the documentation should make explicitly clear that this panics if either of the following are true:

  1. range.end > slice.len()
  2. range.end < range.start

Also the documentation should make clear that this does panic, not just that it might, because surely this panic is not UB.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.