File tree 1 file changed +30
-0
lines changed
1 file changed +30
-0
lines changed Original file line number Diff line number Diff line change @@ -61,6 +61,33 @@ error: aborting due to previous error
61
61
There’s a lot of punctuation in that message, but the core of it makes sense:
62
62
you cannot index with an ` i32 ` .
63
63
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
+
64
91
## Iterating
65
92
66
93
Once you have a vector, you can iterate through its elements with ` for ` . There
@@ -87,3 +114,6 @@ API documentation][vec].
87
114
88
115
[ vec ] : ../std/vec/index.html
89
116
[ 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
You can’t perform that action at this time.
0 commit comments