如何从Rust的BigInt中减去1? [英] How does one subtract 1 from a BigInt in Rust?

查看:209
本文介绍了如何从Rust的BigInt中减去1?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望该程序在执行时编译并打印314158:

I'd like this program to compile and print 314158 when executed:

extern crate num;

use num::{BigInt, FromPrimitive, One};

fn main() {
    let p: BigInt = FromPrimitive::from_usize(314159).unwrap();
    let q: BigInt = p - One::one();
    println!("q = {}", q);
} // end main

编译器错误是:

error[E0284]: type annotations required: cannot resolve `<num::BigInt as std::ops::Sub<_>>::Output == num::BigInt`
 --> src/main.rs:7:23
  |
7 |     let q: BigInt = p - One::one();
  |                       ^

推荐答案

关于特征,Rust遵循开放世界假设.根据您的注释,它知道pBigInt.还知道One::one()具有实现One的类型.因此,Rust正在BigInt上寻找一个减法运算符,该运算符将类似One的东西作为参数.

Rust follows an open world hypothesis when it comes to traits. It knows, based on your annotations, that p is BigInt. It also knows that One::one() has a type which implements One. So Rust is looking for a subtraction operator on BigInt which takes a One-like thing as an argument.

num::BigInt as std::ops::Sub<Foo>>

其中Foo实现One.麻烦的是,BigInt以几种不同的方式实现了Sub ,因此Rust不知道您是否要从p减去i32u64或另一个BigInt.

where Foo implements One. Trouble is, BigInt implements Sub in several different ways, so Rust doesn't know whether you're trying to subtract a i32, a u64, or another BigInt from p.

一个答案是要更明确地说明您的类型.

One answer is to be more explicit with your types.

let p: BigInt = FromPrimitive::from_usize(314159).unwrap();
let one: BigInt = One::one();
let q: BigInt = p - one;

但是,更简洁地说,您可以利用BigInt实现One的事实,并以这种方式帮助编译器进行类型推断.

However, more succinctly, you may take advantage of the fact that BigInt implements One and help the compiler with type inference that way.

let p: BigInt = FromPrimitive::from_usize(314159).unwrap();
let q: BigInt = p - BigInt::one();

(感谢@loganfsmyth,提供后一种解决方案!)

(Thanks, @loganfsmyth, for this latter solution!)

这篇关于如何从Rust的BigInt中减去1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆