Skip to content

Commit 5b9dd6a

Browse files
committed
Document bounds checking in the book
1 parent 2e48b59 commit 5b9dd6a

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)