Skip to content

Commit df33fc3

Browse files
Add more explanation on vec type
1 parent 43ddfbd commit df33fc3

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

src/libcollections/vec.rs

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,49 @@ use super::range::RangeArgument;
135135
/// }
136136
/// ```
137137
///
138+
/// # Indexing
139+
///
140+
/// The Vec type allows to access values by index, because it implements the
141+
/// `Index` trait. An example will be more explicit:
142+
///
143+
/// ```
144+
/// let v = vec!(0, 2, 4, 6);
145+
/// println!("{}", v[1]); // it will display '2'
146+
/// ```
147+
///
148+
/// However be careful: if you try to access an index which isn't in the Vec,
149+
/// your software will panic! You cannot do this:
150+
///
151+
/// ```ignore
152+
/// let v = vec!(0, 2, 4, 6);
153+
/// println!("{}", v[6]); // it will panic!
154+
/// ```
155+
///
156+
/// In conclusion: always check if the index you want to get really exists
157+
/// before doing it.
158+
///
159+
/// # Slicing
160+
///
161+
/// A Vec can be mutable. Slices, on the other hand, are read-only objects.
162+
/// To get a slice, use "&". Example:
163+
///
164+
/// ```
165+
/// fn read_slice(slice: &[usize]) {
166+
/// // ...
167+
/// }
168+
///
169+
/// let v = vec!(0, 1);
170+
/// read_slice(&v);
171+
///
172+
/// // ... and that's all!
173+
/// // you can also do it like this:
174+
/// let x : &[usize] = &v;
175+
/// ```
176+
///
177+
/// In Rust, it's more common to pass slices as arguments rather than vectors
178+
/// when you just want to provide a read access. The same goes for String and
179+
/// &str.
180+
///
138181
/// # Capacity and reallocation
139182
///
140183
/// The capacity of a vector is the amount of space allocated for any future

0 commit comments

Comments
 (0)