Rust 泛型函数接受原始整数和地毯整数

Rust generic function accepting both primitive and rug integers

提问人:KSV 提问时间:7/28/2023 最后编辑:cafce25KSV 更新时间:7/28/2023 访问量:59

问:

我正在尝试编写一个对整数进行操作的泛型函数,它可以接受原始整数或多精度整数(通过)。棘手的一点是,对 rug s 的引用具有惰性算术运算,在转换为整数之前返回不完整的类型。所以我认为像下面这样的东西会起作用,但我似乎无法获得正确的生存期设置(并且 rust-analyzer 在提供帮助方面并不是非常冗长):rugInteger

use rug::Integer;
use std::ops::Mul;

fn mymul<T, S>(x: &T, y: &T) -> T
where
    T: 'static + From<S>,
    for<'a> &'a T: Mul<&'a T, Output = S>,
{
    T::from(x * y)
}

fn main() {
    let x: u64 = 3847381;
    let y: u64 = 28478195;
    let rug_x = Integer::from(x);
    let rug_y = Integer::from(y);
    println!("{} == {:?}", mymul(&x, &y), mymul(&rug_x, &rug_y));
}

有错误

error[E0308]: mismatched types
  --> src/main.rs:22:43
   |
22 |     println!("{} == {:?}", mymul(&x, &y), mymul(&rug_x, &rug_y));
   |                                           ^^^^^^^^^^^^^^^^^^^^^ one type is more general than the other
   |
   = note: expected struct `integer::arith::MulIncomplete<'a>`
              found struct `integer::arith::MulIncomplete<'_>`
note: the lifetime requirement is introduced here
  --> src/main.rs:12:31
   |
12 |     for<'a> &'a T: Mul<&'a T, Output = S>,
   |                               ^^^^^^^^^^

知道如何正确地做这种事情吗?

Rust BigInteger 特征边界

评论

0赞 Ivan C 7/28/2023
请在完整的错误消息中进行编辑。
1赞 Chayim Friedman 7/28/2023
Nit:一般来说,你不应该绑定,而应该绑定。FromInto
0赞 Chayim Friedman 7/28/2023
你为什么要引入绑定?T: 'static
0赞 KSV 7/28/2023
编译器在此代码的演变过程中的某个时刻提出了建议,但您的解决方案显然是正确的。谢谢!

答:

3赞 Chayim Friedman 7/28/2023 #1

使用 HRTB 指定此函数的正确方法是:

fn mymul<T>(x: &T, y: &T) -> T
where
    for<'a> &'a T: Mul<&'a T>,
    for<'a> <&'a T as Mul<&'a T>>::Output: Into<T>,
{
    (x * y).into()
}