@@ -55,12 +55,16 @@ pub fn repeat<T: Clone, const N: usize>(val: T) -> [T; N] {
5555 from_trusted_iterator ( repeat_n ( val, N ) )
5656}
5757
58- /// Creates an array of type [T; N], where each element `T` is the returned value from `cb`
59- /// using that element's index.
58+ /// Creates an array where each element is produced by calling `gen` with
59+ /// that element's index.
6060///
61- /// # Arguments
61+ /// This is essentially the same as writing
62+ /// ```text
63+ /// [gen(0), gen(1), gen(2), …, gen(N - 2), gen(N - 1)]
64+ /// ```
65+ /// and is similar to `(0..i).map(gen)`, just for arrays not iterators.
6266///
63- /// * `cb`: Callback where the passed argument is the current array index .
67+ /// If `N == 0`, this produces an empty array without ever calling `gen` .
6468///
6569/// # Example
6670///
@@ -82,6 +86,23 @@ pub fn repeat<T: Clone, const N: usize>(val: T) -> [T; N] {
8286/// // indexes are: 0 1 2 3 4
8387/// assert_eq!(bool_arr, [true, false, true, false, true]);
8488/// ```
89+ ///
90+ /// You can also capture things, for example to create an array full of clones
91+ /// where you can't just use `[item; N]` because it's not `Copy`:
92+ /// ```
93+ /// # // TBH `array::repeat` would be better for this, but it's not stable yet.
94+ /// let my_string = String::from("Hello");
95+ /// let clones: [String; 42] = std::array::from_fn(|_| my_string.clone());
96+ /// assert!(clones.iter().all(|x| *x == my_string));
97+ /// ```
98+ ///
99+ /// The array is generated in ascending index order, starting from the front
100+ /// and going towards the back, so you can use closures with mutable state:
101+ /// ```
102+ /// let mut state = 1;
103+ /// let a = std::array::from_fn(|_| { let x = state; state *= 2; x });
104+ /// assert_eq!(a, [1, 2, 4, 8, 16, 32]);
105+ /// ```
85106#[ inline]
86107#[ stable( feature = "array_from_fn" , since = "1.63.0" ) ]
87108pub fn from_fn < T , const N : usize , F > ( cb : F ) -> [ T ; N ]
0 commit comments