Search code examples
rustiteratorownershipbignum

How can I make a range of values using BigInt or BigUint in Rust?


I would like to loop through a range of values that have a BigUint type (from the num crate).

How can I do this?

I tried

for i in 0..a {...}

where a is a (borrowed) BigUint type. I got a error about mismatched integer types so I tried this instead:

for i in Zero::zero()..a {...}

But I get different errors depending on if a is borrowed or not. If a is borrowed then I get this in the errors:

|    for i in Zero::zero()..(a) {
|             ^^^^^^^^^^ the trait `num::Zero` is not implemented for `&num::BigUint`

If a is not borrowed, then this is the error:

|    for i in Zero::zero()..(a) {
|             ^^^^^^^^^^^^^^^^^ the trait `std::iter::Step` is not implemented for `num::BigUint`

Solution

  • It seems this is not yet supported in the num crate, because of unstability of Step trait .

    What you can do is to use num-iter crate with its range functions.

    use num::BigUint;
    
    fn main() {
        for i in num_iter::range_inclusive(BigUint::from(0u64), BigUint::from(2u64)) {
            println!("{}", i);
        }
    }