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

问题描述 投票:3回答:1

我试着编译以下代码:

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特性,并且不提供这样一个矛盾的错误消息。我怎么能从这里走得更远?

random rust alphanumeric
1个回答
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>(); 
}
© www.soinside.com 2019 - 2024. All rights reserved.