Generate random string or bytes in Rustrust/random-string-or-bytesAn 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}Disclaimer
The code snippet is provided for reference and learning purposes only. Users should use it at their own risk. I, along with the related developers, shall not be held responsible for any direct or indirect losses caused by the use of this code snippet, including but not limited to data loss, computer malfunctions, program errors, etc.