我尝试编译以下代码:
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
特质,而不提供这种矛盾的错误消息。我该怎么走?
答案 0 :(得分:5)
如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>();
}