[英]How does one subtract 1 from a BigInt in Rust?
I'd like this program to compile and print 314158
when executed: 我希望该程序在执行时编译并打印
314158
:
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
The compiler error is: 编译器错误是:
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 follows an open world hypothesis when it comes to traits. 关于特征,Rust遵循开放世界假设。 It knows, based on your annotations, that
p
is BigInt
. 根据您的注释,它知道
p
是BigInt
。 It also knows that One::one()
has a type which implements One
. 它还知道
One::one()
具有实现One
的类型。 So Rust is looking for a subtraction operator on BigInt
which takes a One
-like thing as an argument. 因此,Rust正在
BigInt
上寻找一个减法运算符,该运算符将类似于One
的东西作为参数。
num::BigInt as std::ops::Sub<Foo>>
where Foo
implements One
. Foo
实现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
. 麻烦的是,
BigInt
以几种不同的方式实现Sub
,因此Rust不知道您是否要从p
减去i32
, u64
或另一个BigInt
。
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;
However, more succinctly, you may take advantage of the fact that BigInt
implements One
and help the compiler with type inference that way. 但是,更简洁地说,您可以利用
BigInt
实现One
的事实,并以这种方式帮助编译器进行类型推断。
let p: BigInt = FromPrimitive::from_usize(314159).unwrap();
let q: BigInt = p - BigInt::one();
(Thanks, @loganfsmyth, for this latter solution!) (感谢@loganfsmyth,这是后一种解决方案!)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.