Generate A String Of Random Numbers And Letters In Rust

rust

```cargo
[dependencies]
rand = "0.8"
```

use rand::{thread_rng, Rng};

fn main() {
  let random_string = random_string(20);
  println!("{}", random_string);
}

fn random_string(length: usize) -> String {
  let mut rng = thread_rng();
  let mut items = (65..=90).map(|c| 
    char::from_u32(c).unwrap().to_string()).collect::<Vec<String>>();
  (0..=9).for_each(|n| items.push(n.to_string()));
  let count = items.len();
  (0..length).map(|_| 
    items[rng.gen_range(0..count)].clone()).collect::<Vec<String>>().join("")
}
            
7BZ761BAEGLEH0DKR4NG
        

I'm after a string of random numbers and letters to use in Neopolgen post NeoJinja and Pre-Attentive Perception. I expect there's Rust crates that'll get what I want but I wanted to go through the exercise myself to play with some randomness in Rust. This is what I ended up with.

That's based on the Rust Rand Bookrrb and the rand crate docsrgr. I don't have a full grasp on this stuff though. As I'm reading it, using Uniformruni sounds like it's more effificent if you're doing it multiple times. I am, but I'm not worried about it for getting this to work. If I understand right, the level or randomness is the same.

If you know more about this stuff and I'm off base please hit me up on Mastodonmast.

Footnotes

  • rrb
    The Rust Random Book
  • rgr
    Rust rand create: gen_range
  • runi
    Rust rand create: Uniform
  • mast
    TheIdOfAlan on Mastodon