问题
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
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();
| ^
回答1:
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>>
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;
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();
(Thanks, @loganfsmyth, for this latter solution!)
来源:https://stackoverflow.com/questions/51371674/how-does-one-subtract-1-from-a-bigint-in-rust