4 ms·
Sorry but the typing part is incorrect. Look at the signature of from_fn: pub fn from_fn<T, const N: usize, F>(cb: F) -> [T; N] where F: FnMut
by orlp 4y ago
Sorry but the typing part is incorrect. Look at the signature of from_fn:
pub fn from_fn<T, const N: usize, F>(cb: F) -> [T; N]
where
F: FnMut(usize) -> T,
It takes a function with signature f(usize) -> T. So |i| i gets inferred to be a function taking a usize, and returning a usize (since we just give the argument straight back). So it infers [usize; 5] in the end.
For example core::array::from_fn(|i| i) == [0i32] wouldn't even compile.
- dymk 4y agoGood catch. The parent comment is interested in how the array length is inferred though, so I'm going to consider the explanation close enough (that it's an i32 or usize isn't particularly relevant).
- wongarsu 4y agoYou are right. The parameter given to the closure is the array index, which is usize. Since that's returned straight back the returned value is also of type usize, and the integers in the array in the assert are inferred to also be usize. Which is in a way an even stronger showcase of Rust's type inference: the length of the variable is inferred from the constant array, but the type of the content of the constant array is inferred by the type of the content of the variable, which is inferred from the type of the closure.