在Rust中,如何在BigInt上使用已实现的特征FromStr?

问题描述 投票:4回答:4

我想让这个程序编译:

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

fn main () {
    println!("{}", BigInt::from_str("1"));
}

rustc的输出是

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

我怀疑我做了一些非常错误的事情,但我试图搜索示例并尝试了一系列不同的更改,而我尝试过的任何工作都没有。

如何更改源代码以便编译?

rust
4个回答
5
投票

在最新版本的Rust中删除了普通函数from_str。此功能现在仅作为FromStr特征的方法提供。

解析值的现代方法是.parsestr方法:

extern crate num;
use num::bigint::BigInt;

fn main() {
    match "1".parse::<BigInt>() {
        Ok(n)  => println!("{}", n),
        Err(_) => println!("Error")
    }
}

4
投票
extern crate num;
use num::bigint::BigInt;

fn main () {
    println!("{}", from_str::<BigInt>("1"));
}

在函数调用中,您需要将::放在尖括号之前。


1
投票

这适用于直接调用特征实现,而不是通过实用程序函数。这不是惯用语。

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

fn main () {
    let x : Result<BigInt,_> = FromStr::from_str("1");
    println!("{}", x);
}

1
投票

您的原始代码几乎按原样运行:

use num::bigint::BigInt; // 0.2.0
use std::str::FromStr;

fn main() {
    println!("{:?}", BigInt::from_str("1"));
}

你需要切换到std::str::FromStrfrom_str返回一个需要Result{:?})格式化的Debug

© www.soinside.com 2019 - 2024. All rights reserved.