From d9e8d93d38b999af23767251d0a43886055d776e Mon Sep 17 00:00:00 2001 From: Trevor Gross Date: Fri, 17 Jun 2022 16:09:55 -0400 Subject: [PATCH] Add example for `array.get()` --- src/primitives/array.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/primitives/array.md b/src/primitives/array.md index d0cd50e26a..841c71c14d 100644 --- a/src/primitives/array.md +++ b/src/primitives/array.md @@ -53,6 +53,17 @@ fn main() { assert_eq!(&empty_array, &[]); assert_eq!(&empty_array, &[][..]); // same but more verbose + // Arrays can be safely accessed using `.get`, which returns an + // `Option`. This can be matched as shown below, or used with + // `.expect()` if you would like the program to exit with a nice + // message instead of happily continue. + for i in 0..xs.len() + 1 { // OOPS, one element too far + match xs.get(i) { + Some(xval) => println!("{}: {}", i, xval), + None => println!("Slow down! {} is too far!", i), + } + } + // Out of bound indexing causes compile error //println!("{}", xs[5]); }