Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,942 questions

51,880 answers

573 users

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
...