How does one subtract 1 from a BigInt in Rust?

♀尐吖头ヾ 提交于 2019-12-24 08:06:47

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!