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

pxq42qpu  于 2023-01-02  发布在  其他
关注(0)|答案(4)|浏览(219)

我试着编译下面的代码:

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 trait,而不提供这样一个矛盾的错误消息。我该如何进一步呢?

ecfdbz9o

ecfdbz9o1#

正如兰德0.5.0文档中所解释的那样,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);
}
dnph8jn4

dnph8jn42#

随着兰德0.8.4的引入,rand现在包含了DistString,它包含了一个more efficient方法来采样随机字母数字字符串。

use rand::distributions::{Alphanumeric, DistString};

let string = Alphanumeric.sample_string(&mut rand::thread_rng(), 16);
println!("{}", string);
8tntrjer

8tntrjer3#

您可以使用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));
enxuqcxy

enxuqcxy4#

一个带有自定义字符集rand板条箱的示例:

use rand::Rng;
use std::iter;

fn generate(len: usize) -> String {
    const CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    let mut rng = rand::thread_rng();
    let one_char = || CHARSET[rng.gen_range(0..CHARSET.len())] as char;
    iter::repeat_with(one_char).take(len).collect()
}

相关问题