home ~ projects ~ socials

Get Some Random Characters From A UUID

I'm not sure why I did this originally. I think it's becuase I wanted random numbers and letters. I've since made code that does exactly that.

Also, this breaks if you ask for too many characters (see notes). The new code on the other page doesn't have that problem.

```cargo
[dependencies]
uuid = { version = "1.7.0", features = ["v4"] }
```

use uuid::Uuid;

fn main() {
    // must be less than 32. See notes
    let the_string = random_string(32);
    println!("{}", the_string);
}

fn random_string(count: u8) -> String {
    let base = Uuid::new_v4().simple().to_string();
    base.get(0..count.into()).unwrap().to_string()
}
Output:
ec4b10b36ad745c6942ea8aed505105f

Notes

  • This is not guaranteed to be unique, it's just a way to get a few random characters.
  • As noted in the code, trying to get more than 32 characters will crash. Making a version that returns an option can address that if you need it
  • This returns a string with numbers and random lower case letters
  • It's generated off a UUID, but there's no dashes in it
-- end of line --

References