diff options
| author | Steve Klabnik <steve@steveklabnik.com> | 2015-09-30 13:46:58 -0400 |
|---|---|---|
| committer | Steve Klabnik <steve@steveklabnik.com> | 2015-09-30 13:46:58 -0400 |
| commit | 3ef9c1d5f9872c1de797bf4e594f4d54a04ef650 (patch) | |
| tree | 9b5b9fe00ab4b9bce59744ac4d9cd276e1341255 | |
| parent | 3e6d7243ae9749eff27fd320cb422e42291e79d4 (diff) | |
| download | rust-3ef9c1d5f9872c1de797bf4e594f4d54a04ef650.tar.gz rust-3ef9c1d5f9872c1de797bf4e594f4d54a04ef650.zip | |
Mention that you can only index with usize
Fixes #28693
| -rw-r--r-- | src/doc/trpl/vectors.md | 29 |
1 files changed, 29 insertions, 0 deletions
diff --git a/src/doc/trpl/vectors.md b/src/doc/trpl/vectors.md index d8b894a2f65..7b826f08ae6 100644 --- a/src/doc/trpl/vectors.md +++ b/src/doc/trpl/vectors.md @@ -32,6 +32,35 @@ println!("The third element of v is {}", v[2]); The indices count from `0`, so the third element is `v[2]`. +It’s also important to note that you must index with the `usize` type: + +```ignore +let v = vec![1, 2, 3, 4, 5]; + +let i: usize = 0; +let j: i32 = 0; + +// works +v[i]; + +// doesn’t +v[j]; +``` + +Indexing with a non-`usize` type gives an error that looks like this: + +```text +error: the trait `core::ops::Index<i32>` is not implemented for the type +`collections::vec::Vec<_>` [E0277] +v[j]; +^~~~ +note: the type `collections::vec::Vec<_>` cannot be indexed by `i32` +error: aborting due to previous error +``` + +There’s a lot of punctuation in that message, but the core of it makes sense: +you cannot index with an `i32`. + ## Iterating Once you have a vector, you can iterate through its elements with `for`. There |
