[英]In Rust, how do I use implemented trait FromStr on BigInt?
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 但是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
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. 普通函数from_str
已在Rust的最新版本中删除。 This function is now only available as a method of the FromStr
trait. 现在,此功能仅可用作FromStr
特征的方法。
The modern way to parse values is the .parse
method of str
: 解析值的.parse
方法是str
的.parse
方法:
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. 你需要切换到std::str::FromStr
和from_str
返回一个Result
这就需要{:?}
( Debug
)格式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.