【问题标题】:How can I make a range of values using BigInt or BigUint in Rust?如何在 Rust 中使用 BigInt 或 BigUint 生成一系列值?
【发布时间】:2019-06-23 08:57:03
【问题描述】:

我想遍历一系列具有BigUint 类型的值(来自num crate)。

我该怎么做?

我试过了

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

其中a 是(借用的)BigUint 类型。我收到关于不匹配整数类型的错误,所以我尝试了这个:

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

但我得到不同的错误取决于a 是否被借用。 如果a 是借用的,那么我会在错误中得到这个:

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

如果 a 没有被借用,那么这就是错误:

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

【问题讨论】:

    标签: rust iterator ownership bignum


    【解决方案1】:

    num crate 似乎尚不支持此功能,因为unstability of Step trait

    您可以做的是使用num-iter crate 及其范围函数。

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

    【讨论】:

    • 有意思,Step trait 怎么不稳定?
    • @user668074 “不稳定”并不意味着它有错误或无法正常工作,它只是意味着设计可能仍然会发生变化,因此它仅在夜间 Rust 构建中可用,它不会不要承担向后兼容的负担。 Rust 团队不会急于稳定新的 API,因为如果一开始就设计不正确,以后很难更改它们。
    • @PeterHall,啊,我明白了。很高兴知道。希望它很快就能正确实施。
    • 我开始使用它,但我不确定这是一个好主意。一方面,RangeInclusive 需要 T: ToPrimitive。 BigInt 确实实现了 ToPrimitive,但大多数时候它会返回 None。而 step_by 实现使用 usize 作为 step 的固定类型,所以这几乎没用。
    • @JamesMoore,所以这个问题是几年前发布的。该问题是否仍然引发相关问题?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-21
    • 1970-01-01
    • 1970-01-01
    • 2023-02-24
    • 2014-03-12
    • 1970-01-01
    • 2018-08-22
    相关资源
    最近更新 更多