How to initialize char array with random characters in Rust

1 Answer

0 votes
use rand::prelude::*;
use rand::rngs::StdRng;
use rand::SeedableRng;
use std::time::{SystemTime, UNIX_EPOCH};

fn main() {
    // Get a seed from system time
    let seed = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .expect("Time went backwards")
        .as_secs();
    
    // Create a deterministic random number generator with the seed
    let mut rng = StdRng::seed_from_u64(seed);
    
    let charset: &[u8] = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    let charset_len = charset.len();
    
    let random_chars: Vec<char> = (0..10)
        .map(|_| {
            // Generate a random u8 and map it to the charset range
            let random_byte: u8 = rng.next_u32() as u8;
            let idx = (random_byte as usize) % charset_len;
            charset[idx] as char
        })
        .collect();
    
    println!("{:?}", random_chars);
}

 
      
/*
run:
   
['O', 'v', 't', 'S', 'b', 'm', '2', '7', '7', 'c']
     
*/

 



answered Mar 11, 2025 by avibootz
...