Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 424
M. Clabaut Avatar asked Jan 20 '19 10:01

M. Clabaut


People also ask

How do you generate random strings?

Using the random index number, we have generated the random character from the string alphabet. We then used the StringBuilder class to append all the characters together. If we want to change the random string into lower case, we can use the toLowerCase() method of the String .


2 Answers

As explained in the rand 0.5.0 docs, gen_ascii_chars is deprecated and you should use sample_iter(&Alphanumeric) instead.

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);
}
like image 159
M. Clabaut Avatar answered Oct 07 '22 12:10

M. Clabaut


You can use random-string crate with your charset. You can install it by including random-string library in your Cargo.toml.

Take a look at the example:

// 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));
like image 29
Felierix Avatar answered Oct 07 '22 12:10

Felierix