Skip to content

Commit 15ee0e9

Browse files
committed
Rollup merge of #28765 - steveklabnik:gh28693, r=nikomatsakis
Fixes #28693
2 parents a8ed0bf + 3ef9c1d commit 15ee0e9

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

src/doc/trpl/vectors.md

+29
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,35 @@ println!("The third element of v is {}", v[2]);
3232

3333
The indices count from `0`, so the third element is `v[2]`.
3434

35+
It’s also important to note that you must index with the `usize` type:
36+
37+
```ignore
38+
let v = vec![1, 2, 3, 4, 5];
39+
40+
let i: usize = 0;
41+
let j: i32 = 0;
42+
43+
// works
44+
v[i];
45+
46+
// doesn’t
47+
v[j];
48+
```
49+
50+
Indexing with a non-`usize` type gives an error that looks like this:
51+
52+
```text
53+
error: the trait `core::ops::Index<i32>` is not implemented for the type
54+
`collections::vec::Vec<_>` [E0277]
55+
v[j];
56+
^~~~
57+
note: the type `collections::vec::Vec<_>` cannot be indexed by `i32`
58+
error: aborting due to previous error
59+
```
60+
61+
There’s a lot of punctuation in that message, but the core of it makes sense:
62+
you cannot index with an `i32`.
63+
3564
## Iterating
3665

3766
Once you have a vector, you can iterate through its elements with `for`. There

0 commit comments

Comments
 (0)