Skip to content

Commit 35b6461

Browse files
committed
Auto merge of #30310 - mbrubeck:doc-vec-bounds, r=steveklabnik
r? @steveklabnik Currently neither the API docs nor the book clearly explain that out-of-bounds array indexing causes a panic. Since this is fairly important and seems to surprise a number of new Rust programmers, I think it's worth adding to both places. (But if you think it would be better to put this info in the API docs only, that's fine too.) Some specific things I'd like feedback on: * The new text here talks about panicking, which hasn't been formally introduced at this point in chapter 5 (though it has been mentioned in previous sections too). * Similarly the `Vec::get` example uses `Option<T>` which hasn't been fully introduced yet. Should we leave out this example?
2 parents 1ddaf8b + 5b9dd6a commit 35b6461

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

src/doc/book/vectors.md

+30
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,33 @@ error: aborting due to previous error
6161
There’s a lot of punctuation in that message, but the core of it makes sense:
6262
you cannot index with an `i32`.
6363

64+
## Out-of-bounds Access
65+
66+
If you try to access an index that doesn’t exist:
67+
68+
```ignore
69+
let v = vec![1, 2, 3];
70+
println!("Item 7 is {}", v[7]);
71+
```
72+
73+
then the current thread will [panic] with a message like this:
74+
75+
```text
76+
thread '<main>' panicked at 'index out of bounds: the len is 3 but the index is 7'
77+
```
78+
79+
If you want to handle out-of-bounds errors without panicking, you can use
80+
methods like [`get`][get] or [`get_mut`][get_mut] that return `None` when
81+
given an invalid index:
82+
83+
```rust
84+
let v = vec![1, 2, 3];
85+
match v.get(7) {
86+
Some(x) => println!("Item 7 is {}", x),
87+
None => println!("Sorry, this vector is too short.")
88+
}
89+
```
90+
6491
## Iterating
6592

6693
Once you have a vector, you can iterate through its elements with `for`. There
@@ -87,3 +114,6 @@ API documentation][vec].
87114

88115
[vec]: ../std/vec/index.html
89116
[generic]: generics.html
117+
[panic]: concurrency.html#panics
118+
[get]: http://doc.rust-lang.org/std/vec/struct.Vec.html#method.get
119+
[get_mut]: http://doc.rust-lang.org/std/vec/struct.Vec.html#method.get_mut

0 commit comments

Comments
 (0)