我想让这个程序编译:
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中删除了普通函数from_str
。此功能现在仅作为FromStr
特征的方法提供。
解析值的现代方法是.parse
的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"));
}
在函数调用中,您需要将::
放在尖括号之前。
这适用于直接调用特征实现,而不是通过实用程序函数。这不是惯用语。
extern crate num;
use num::bigint::BigInt;
use std::from_str::FromStr;
fn main () {
let x : Result<BigInt,_> = FromStr::from_str("1");
println!("{}", x);
}
您的原始代码几乎按原样运行:
use num::bigint::BigInt; // 0.2.0
use std::str::FromStr;
fn main() {
println!("{:?}", BigInt::from_str("1"));
}
你需要切换到std::str::FromStr
和from_str
返回一个需要Result
({:?}
)格式化的Debug
。