Skip to content

Commit 1095df2

Browse files
authored
Merge pull request #1554 from tgross35/patch-1
Add example for `array.get()`
2 parents feb8f91 + d9e8d93 commit 1095df2

File tree

1 file changed

+11
-0
lines changed

1 file changed

+11
-0
lines changed

src/primitives/array.md

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,17 @@ fn main() {
5353
assert_eq!(&empty_array, &[]);
5454
assert_eq!(&empty_array, &[][..]); // same but more verbose
5555
56+
// Arrays can be safely accessed using `.get`, which returns an
57+
// `Option`. This can be matched as shown below, or used with
58+
// `.expect()` if you would like the program to exit with a nice
59+
// message instead of happily continue.
60+
for i in 0..xs.len() + 1 { // OOPS, one element too far
61+
match xs.get(i) {
62+
Some(xval) => println!("{}: {}", i, xval),
63+
None => println!("Slow down! {} is too far!", i),
64+
}
65+
}
66+
5667
// Out of bound indexing causes compile error
5768
//println!("{}", xs[5]);
5869
}

0 commit comments

Comments
 (0)