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

只谈情不闲聊 提交于 2020-02-22 06:11:00

问题


I tried to compile the following code:

extern crate rand; // 0.6
use rand::Rng;

fn main() {
    rand::thread_rng()
        .gen_ascii_chars()
        .take(10)
        .collect::<String>();
}

but cargo build says:

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()
  |          ^^^^^^^^^^^^^^^

The Rust compiler asks me to remove the use rand::Rng; clause, at the same time complaining that there is no gen_ascii_chars method. I would expect Rust to just use rand::Rng trait, and to not provide such a contradictory error messages. How can I go further from here?


回答1:


As explained in rand 0.5.0 docs gen_ascii_chars is deprecated.

As of 0.6.0, the code should be:

extern crate rand;

use rand::Rng; 
use rand::distributions::Alphanumeric;

fn main() {
    rand::thread_rng()
        .sample_iter(&Alphanumeric)
        .take(10)
        .collect::<String>(); 
}


来源:https://stackoverflow.com/questions/54275459/how-do-i-create-a-random-string-by-sampling-from-alphanumeric-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!