Skip to content

Commit 40d7596

Browse files
committed
Implement Vec::from_fn
1 parent 91ab308 commit 40d7596

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

library/alloc/src/vec/mod.rs

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -745,6 +745,58 @@ impl<T> Vec<T> {
745745
unsafe { Self::from_parts_in(ptr, length, capacity, Global) }
746746
}
747747

748+
/// Creates a `Vec<T>` where each element is produced by calling `f` with
749+
/// that element's index while walking forward through the `Vec<T>`.
750+
///
751+
/// This is essentially the same as writing
752+
///
753+
/// ```text
754+
/// vec![f(0), f(1), f(2), …, f(length - 2), f(length - 1)]
755+
/// ```
756+
/// and is similar to `(0..i).map(f)`, just for `Vec<T>`s not iterators.
757+
///
758+
/// If `length == 0`, this produces an empty `Vec<T>` without ever calling `f`.
759+
///
760+
/// # Example
761+
///
762+
/// ```rust
763+
/// #![feature(vec_from_fn)]
764+
///
765+
/// let vec = Vec::from_fn(5, |i| i);
766+
///
767+
/// // indexes are: 0 1 2 3 4
768+
/// assert_eq!(vec, [0, 1, 2, 3, 4]);
769+
///
770+
/// let vec2 = Vec::from_fn(8, |i| i * 2);
771+
///
772+
/// // indexes are: 0 1 2 3 4 5 6 7
773+
/// assert_eq!(vec2, [0, 2, 4, 6, 8, 10, 12, 14]);
774+
///
775+
/// let bool_vec = Vec::from_fn(5, |i| i % 2 == 0);
776+
///
777+
/// // indexes are: 0 1 2 3 4
778+
/// assert_eq!(bool_vec, [true, false, true, false, true]);
779+
/// ```
780+
///
781+
/// The `Vec<T>` is generated in ascending index order, starting from the front
782+
/// and going towards the back, so you can use closures with mutable state:
783+
/// ```
784+
/// #![feature(vec_from_fn)]
785+
///
786+
/// let mut state = 1;
787+
/// let a = Vec::from_fn(6, |_| { let x = state; state *= 2; x });
788+
///
789+
/// assert_eq!(a, [1, 2, 4, 8, 16, 32]);
790+
/// ```
791+
#[inline]
792+
#[unstable(feature = "vec_from_fn", reason = "new API", issue = "149698")]
793+
pub fn from_fn<F>(length: usize, f: F) -> Self
794+
where
795+
F: FnMut(usize) -> T,
796+
{
797+
(0..length).map(f).collect()
798+
}
799+
748800
/// Decomposes a `Vec<T>` into its raw components: `(pointer, length, capacity)`.
749801
///
750802
/// Returns the raw pointer to the underlying data, the length of

0 commit comments

Comments
 (0)