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

How do I create a random String by sampling from alphanumeric characters?

我尝试编译以下代码:

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 已弃用,您应该改用 sample_iter(&Alphanumeric)

use rand::{distributions::Alphanumeric, Rng}; // 0.8

fn main() {
    let s: String = rand::thread_rng()
        .sample_iter(&Alphanumeric)
        .take(7)
        .map(char::from)
        .collect();
    println!("{}", s);
}

您可以将 random-string crate 与您的字符集一起使用。您可以通过在 Cargo.toml.

中包含 random-string 库来安装它

看看例子:

// Import generate function
use random_string::generate;

// Your custom charset
let charset = "abcdefghijklmnopqrstuvwxyz";

// Syntax:
// random_string::generate(length, your_charset);

// Usage:
println!("{}", generate(6, charset));