سؤال

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::from_str("1"));
}

But the output from rustc is

testing.rs:6:20: 6:36 error: unresolved name `BigInt::from_str`.
testing.rs:6     println!("{}", BigInt::from_str("1"));
                                ^~~~~~~~~~~~~~~~
note: in expansion of format_args!
<std macros>:2:23: 2:77 note: expansion site
<std macros>:1:1: 3:2 note: in expansion of println!
testing.rs:6:5: 6:43 note: expansion site
error: aborting due to previous error

I suspect I am doing something trivially wrong, but I've tried searching for examples and tried a bunch of different changes and nothing I tried worked.

How do I change my source code so this compiles?

هل كانت مفيدة؟

المحلول

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")
    }
}

نصائح أخرى

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.

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);
}

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top