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

1

5

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`
Vitrine answered 23/6, 2019 at 8:57 Comment(0)
A
6

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);
    }
}
Amorete answered 23/6, 2019 at 9:14 Comment(6)
Interesting, how is the Step trait unstable?Vitrine
@Vitrine "Unstable" doesn't mean it has bugs or doesn't work properly, it just means the design might still change, and so it is only available in a nightly Rust build, which doesn't carry the burden of backwards compatibility. The Rust team doesn't rush into stabilising new APIs because it's hard to change them later if they weren't designed right the first time around.Excrescency
@PeterHall, Ah, I see. Good to know. Hopefully it is implemented properly soon.Vitrine
I started to use this, but I'm not sure it's a great idea. For one, RangeInclusive<T> requires T: ToPrimitive. BigInt does implement ToPrimitive, but it's going to return None most of the time. And the step_by implementation uses usize as the fixed type for the step, so that's pretty much useless.Intravasation
@JamesMoore, So this question was posted a few years ago. Does the question still raise a relevant issue?Vitrine
Yes, IMHO. It's still very unclear what the right way is to use ranges with bigints.Intravasation

© 2022 - 2024 — McMap. All rights reserved.