In Rust, how do I use implemented trait FromStr on BigInt?

前端 未结 4 1376
长情又很酷
长情又很酷 2020-12-19 17:03

I am trying to get this program to compile:

extern crate num;
use num::bigint::BigInt;
use std::from_str::FromStr;

fn main () {
    println!(\"{}\", BigInt:         


        
相关标签:
4条回答
  • 2020-12-19 17:28

    The plain function from_str has been removed in recent versions of Rust. This function is now only available as a method of the FromStr trait.

    The modern way to parse values is the .parse method of str:

    extern crate num;
    use num::bigint::BigInt;
    
    fn main() {
        match "1".parse::<BigInt>() {
            Ok(n)  => println!("{}", n),
            Err(_) => println!("Error")
        }
    }
    
    0 讨论(0)
  • 2020-12-19 17:32
    extern crate num;
    use num::bigint::BigInt;
    
    fn main () {
        println!("{}", from_str::<BigInt>("1"));
    }
    

    In function calls, you need to put :: before the angle brackets.

    0 讨论(0)
  • 2020-12-19 17:37

    Your original code works almost as-is:

    use num::bigint::BigInt; // 0.2.0
    use std::str::FromStr;
    
    fn main() {
        println!("{:?}", BigInt::from_str("1"));
    }
    

    You need to switch to std::str::FromStr and from_str returns a Result which requires the {:?} (Debug) formatter.

    0 讨论(0)
  • 2020-12-19 17:47

    This works for calling the trait implementation directly instead of through the utility function. This is not idiomatic.

    extern crate num;
    use num::bigint::BigInt;
    use std::from_str::FromStr;
    
    fn main () {
        let x : Result<BigInt,_> = FromStr::from_str("1");
        println!("{}", x);
    }
    
    0 讨论(0)
提交回复
热议问题