Generate random string or bytes in Rust
rust/random-string-or-bytes
An example of using create::rand and Iterator to generate random string or bytes
1use rand::{thread_rng, Rng};
2
3pub fn generate_random_string(length: usize) -> String {
4    let charset: &[u8] = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
5    let mut rng = thread_rng();
6    let random_string: String = (0..length)
7        .map(|_| {
8            let idx = rng.gen_range(0..charset.len());
9            char::from(charset[idx])
10        })
11        .collect();
12
13    random_string
14}
15
16pub fn generate_random_u8_array(length: usize) -> Vec<u8> {
17    let mut rng = thread_rng();
18    let random_bytes: Vec<u8> = (0..length)
19        .map(|_| rng.gen::<u8>())
20        .collect();
21
22    random_bytes
23}
Unauthorized reproduction of original content on this website is prohibited.