4 ms·
This release contains array::map, which I consider an exciting feature!
by GolDDranks 5y ago
This release contains array::map, which I consider an exciting feature!
- brundolf 5y agoOn the face of it it seems weird to duplicate Iterator methods directly on array (which is iterable), but then it really is a special case because this version (thanks to const generics!) should be able to avoid an allocation, which to my understanding isn't possible with the Iterator version
- CryZe 5y agoWell arrays never allocate in the first place, but you'd need some sort of specialized iterator api that either: - Handles the iterator not being the same size as the array you want to collect the iterator into and turns it into some sort of Result<[T; N], ArrayCollectError>. - By itself knows the exact size of the iterator as part of the iterator type and thus can ensure via the type system that the iterator has exactly as many elements as the array needs.
- nybble41 5y ago> By itself knows the exact size of the iterator as part of the iterator type… std::array::IntoIter<T, N> already satisfies that requirement. The result of mapping over a std::array::IntoIter<T, N> should be std::iter::Map<array::IntoIter<T, N>, F>, which also has the number of elements at the type level and even inherits ExactSizeIterator from array::IntoIter. The problem, I think, is that ExactSizeIterator only says that the size is known at run time; there is no "ConstSizeIterator<N>" trait which would witness that the exact size is known at compile time. If there were then you could potentially collect the items from a ConstSizeIterator<N> (which could be implemented by array::IntoIter<T, N> and inherited by iter::Map<array::IntoIter<T, N>, F>) into an array of N elements without any runtime checks or allocation.
- nextaccountic 5y agoarray.map is not inline, it consumes the array and returns another https://doc.rust-lang.org/std/primitive.array.html#method.map https://doc.rust-lang.org/std/primitive.array.html#method.ma... But yes in the end this is all done in the stack We could have an inline version of map (for arrays and Vec) if we had a way to assert that two types have the same size. This means we can reuse the buffer because all elements will fit.