I think I may just be stupid but I can’t figure this out.
I have a function that takes a generic integer type T, I create a range using that type T and would like to collect that range into a Vec<T>. The issue is that I get the following error method cannot be called on RangeInclusive due to unsatisfied trait bounds. It continues that the following trait bounds were not satisfied: T: Step.
Step in either std::iter::Step or core::iter::Step are both listed as unstable.
I did some digging and it appears that the Step trait is not yet stable. They also mention that the compiler error needs to be changed, but no info on how to actually do what I need to.
Some example Code:
use num_traits::int::PrimInt;
fn collect_range<T>(number: T) -> Vec<T>
where T: PrimtInt + std::ops::Add<Output = T> + std::cmp::PartialOrd + Copy, {
(T::zero()..=number).collect()
}
Error shows up on the collect() in the last line.
My question, is this not possible, do I need to implement something else?
I suppose I can loop through the iterator myself to do it, but seems odd Collect does not work here.
>Solution :
I suppose I can loop through the iterator myself to do it
But you can’t, for the same reason. The range doesn’t implement Iterator unless T: Step.
Excuse the pun, but you can side-step this issue by simply requiring that RangeInclusive<T> must implement Iterator. This also makes many of your bounds on T redundant. Adding the Iterator bound and simplifying the existing bounds gives us this working example:
fn collect_range<T>(number: T) -> Vec<T>
where
T: num_traits::Zero,
std::ops::RangeInclusive<T>: Iterator<Item = T>,
{
(T::zero()..=number).collect()
}
These bounds also more clearly express what’s required for the function to work, so I would argue they aren’t even a workaround — rather, they are the correct bounds based on what the function does.