Reputation: 2419
In Rust, if you attempt to index a slice 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 the panic behavior here is wrong and returning the empty slice &[]
is a more reasonable behavior than panicking, given how the documentation is worded.
Is there somewhere in the documentation that clearly defines the behavior of Index<Range<usize>> for [T]
? Specifically, I feel like the documentation should make explicitly clear that this panics if either of the following are true:
range.end > slice.len()
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.
Upvotes: 2
Views: 450
Reputation: 71430
I believe it is not documented for slices (you are welcomed to send a PR), but at least it's documented for str
, in the trait that powers indexing: SliceIndex
:
Panics
Panics if
begin
orend
does not point to the starting byte offset of a character (as defined byis_char_boundary
), ifbegin > end
, or ifend > len
.
Upvotes: 2