@@ -55,12 +55,16 @@ pub fn repeat<T: Clone, const N: usize>(val: T) -> [T; N] {
55
55
from_trusted_iterator ( repeat_n ( val, N ) )
56
56
}
57
57
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 .
60
60
///
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.
62
66
///
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` .
64
68
///
65
69
/// # Example
66
70
///
@@ -82,13 +86,30 @@ pub fn repeat<T: Clone, const N: usize>(val: T) -> [T; N] {
82
86
/// // indexes are: 0 1 2 3 4
83
87
/// assert_eq!(bool_arr, [true, false, true, false, true]);
84
88
/// ```
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
+ /// ```
85
106
#[ inline]
86
107
#[ 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 ]
88
109
where
89
110
F : FnMut ( usize ) -> T ,
90
111
{
91
- try_from_fn ( NeverShortCircuit :: wrap_mut_1 ( cb ) ) . 0
112
+ try_from_fn ( NeverShortCircuit :: wrap_mut_1 ( f ) ) . 0
92
113
}
93
114
94
115
/// Creates an array `[T; N]` where each fallible array element `T` is returned by the `cb` call.
0 commit comments