我试着编译以下代码:
extern crate rand; // 0.6
use rand::Rng;
fn main() {
rand::thread_rng()
.gen_ascii_chars()
.take(10)
.collect::<String>();
}
但cargo build
说:
warning: unused import: `rand::Rng`
--> src/main.rs:2:5
|
2 | use rand::Rng;
| ^^^^^^^^^
|
= note: #[warn(unused_imports)] on by default
error[E0599]: no method named `gen_ascii_chars` found for type `rand::prelude::ThreadRng` in the current scope
--> src/main.rs:6:10
|
6 | .gen_ascii_chars()
| ^^^^^^^^^^^^^^^
Rust编译器要求我删除use rand::Rng;
子句,同时抱怨没有gen_ascii_chars
方法。我希望Rust只使用rand::Rng
特性,并且不提供这样一个矛盾的错误消息。我怎么能从这里走得更远?
正如在rand 0.5.0 docs中所解释的那样,gen_ascii_chars
已被弃用。
从0.6.0开始,代码应为:
extern crate rand;
use rand::Rng;
use rand::distributions::Alphanumeric;
fn main() {
rand::thread_rng()
.sample_iter(&Alphanumeric)
.take(10)
.collect::<String>();
}