Skip to content

Commit 365d4c9

Browse files
authored
Rollup merge of rust-lang#54860 - mandeep:vec-initialize, r=alexcrichton
Add doc comments about safest way to initialize a vector of zeros This adds more information about the vec! macro as discussed in rust-lang#54628. I think this is a good starting point, but I think additional detail is needed so that we can explain why vec! is safer than the alternatives.
2 parents 44a527a + 1e584bf commit 365d4c9

File tree

1 file changed

+7
-1
lines changed

1 file changed

+7
-1
lines changed

src/liballoc/vec.rs

+7-1
Original file line numberDiff line numberDiff line change
@@ -120,11 +120,17 @@ use raw_vec::RawVec;
120120
/// assert_eq!(vec, [1, 2, 3, 4]);
121121
/// ```
122122
///
123-
/// It can also initialize each element of a `Vec<T>` with a given value:
123+
/// It can also initialize each element of a `Vec<T>` with a given value.
124+
/// This may be more efficient than performing allocation and initialization
125+
/// in separate steps, especially when initializing a vector of zeros:
124126
///
125127
/// ```
126128
/// let vec = vec![0; 5];
127129
/// assert_eq!(vec, [0, 0, 0, 0, 0]);
130+
///
131+
/// // The following is equivalent, but potentially slower:
132+
/// let mut vec1 = Vec::with_capacity(5);
133+
/// vec1.resize(5, 0);
128134
/// ```
129135
///
130136
/// Use a `Vec<T>` as an efficient stack:

0 commit comments

Comments
 (0)