Skip to content

Document bounds checking in the book #30310

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 13, 2015
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions src/doc/book/vectors.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,33 @@ 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`.

## Out-of-bounds Access

If you try to access an index that doesn’t exist:

```ignore
let v = vec![1, 2, 3];
println!("Item 7 is {}", v[7]);
```

then the current thread will [panic] with a message like this:

```text
thread '<main>' panicked at 'index out of bounds: the len is 3 but the index is 7'
```

If you want to handle out-of-bounds errors without panicking, you can use
methods like [`get`][get] or [`get_mut`][get_mut] that return `None` when
given an invalid index:

```rust
let v = vec![1, 2, 3];
match v.get(7) {
Some(x) => println!("Item 7 is {}", x),
None => println!("Sorry, this vector is too short.")
}
```

## Iterating

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

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