如何从Rust的BigInt中减去1? [英] How does one subtract 1 from a BigInt in Rust?
问题描述
我希望该程序在执行时编译并打印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遵循开放世界假设.根据您的注释,它知道p
是BigInt
.还知道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
减去i32
,u64
或另一个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屋!