如何通过从字母数字字符中采样来创建随机字符串?

时间:2019-01-20 10:20:30

标签: random rust alphanumeric

我尝试编译以下代码:

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特质,而不提供这种矛盾的错误消息。我该怎么走?

1 个答案:

答案 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>(); 
}