@@ -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 `f` with
59+ /// that element's index while walking forward through the array .
6060///
61- /// # Arguments
61+ /// This is essentially the same as writing
62+ /// ```text
63+ /// [f(0), f(1), f(2), …, f(N - 2), f(N - 1)]
64+ /// ```
65+ /// and is similar to `(0..i).map(f)`, 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 `f` .
6468///
6569/// # Example
6670///
@@ -82,13 +86,30 @@ 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" ) ]
87- pub fn from_fn < T , const N : usize , F > ( cb : F ) -> [ T ; N ]
108+ pub fn from_fn < T , const N : usize , F > ( f : F ) -> [ T ; N ]
88109where
89110 F : FnMut ( usize ) -> T ,
90111{
91- try_from_fn ( NeverShortCircuit :: wrap_mut_1 ( cb ) ) . 0
112+ try_from_fn ( NeverShortCircuit :: wrap_mut_1 ( f ) ) . 0
92113}
93114
94115/// Creates an array `[T; N]` where each fallible array element `T` is returned by the `cb` call.
0 commit comments