]> git.lizzy.rs Git - rust.git/commitdiff
Rollup merge of #54860 - mandeep:vec-initialize, r=alexcrichton
authorkennytm <kennytm@gmail.com>
Fri, 12 Oct 2018 14:04:04 +0000 (22:04 +0800)
committerGitHub <noreply@github.com>
Fri, 12 Oct 2018 14:04:04 +0000 (22:04 +0800)
Add doc comments about safest way to initialize a vector of zeros

This adds more information about the vec! macro as discussed in #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.

src/liballoc/vec.rs

index 2bc037e3fee126343715212911c8b62e1d28867e..f7a0bbdceafc93325359fbb83a51b413548db0da 100644 (file)
 /// assert_eq!(vec, [1, 2, 3, 4]);
 /// ```
 ///
-/// It can also initialize each element of a `Vec<T>` with a given value:
+/// It can also initialize each element of a `Vec<T>` with a given value.
+/// This may be more efficient than performing allocation and initialization
+/// in separate steps, especially when initializing a vector of zeros:
 ///
 /// ```
 /// let vec = vec![0; 5];
 /// assert_eq!(vec, [0, 0, 0, 0, 0]);
+///
+/// // The following is equivalent, but potentially slower:
+/// let mut vec1 = Vec::with_capacity(5);
+/// vec1.resize(5, 0);
 /// ```
 ///
 /// Use a `Vec<T>` as an efficient stack: