How to impl `FromIterator<{integer}>` for Vec<T>?

I am trying to write a generic function over different unsigned integer types. Here's the code:

fn matrix<R: RngCore, T>(r: usize, c: usize, rng: &mut R) -> Vec<T>
where
    T: num::Integer,
{
    let v = rng
        .sample_iter(Uniform::new(0, 1 << 64))
        .take(r * c)
        .collect::<Vec<T>>();
    v
}

Seems like I haven't satisfied FromIterator<{integer}> trait to use collect. I tried adding + FromIterator<T> to assure that T implements FromIterator but this would not suffice.

How can I make this work?

Your title and the problem are disconnected; the thing that you describe in the title is not possible, but it's not even actually the problem.

The problem is that you are using integer literals for constructing the Uniform distribution; but a type variable like T may be anything, not just a primitive integer. Obviously, if the caller supplied some user-defined type implementing the Integer trait, then sampling a bunch of primitive integers and trying to return them as a vector of arbitrary T wouldn't make any sense.

You'll need to build the distribution from values of type T, not from primitive integers.

2 Likes

Here's a version with alternate bounds. I replaced 1 << 64 with a new function parameter top.

Otherwise you'd need something like i128: Into<T>.

3 Likes

Thanks for the code! Unfortunately can't make two responses as solution.

I changed your code to remove top by replacing num with num_traits :slight_smile:

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.