Search code examples
randomrust

How do I generate a string of random ASCII printable characters with a specific size in Rust?


I'm trying to make a function using Rust that, given an integer, returns a value of type String.

The main problem I'm facing is creating a random character; once I can do that I can concatenate lots of these characters in a loop or something like that and then return the final string.

I've tried to find way to type cast an integer returned from the random function in the rand crate (as you can do in C++) but this does not seem to be the way to go.

What should I do?


Solution

  • The Rust Cookbook shows how this can be accomplished elegantly. Copied from the link above:

    use rand::{thread_rng, Rng};
    use rand::distributions::Alphanumeric;
    
    fn random_string(n: usize) -> String {
        thread_rng().sample_iter(&Alphanumeric)
                    .take(n)
                    .map(char::from)  // From link above, this is needed in later versions
                    .collect()
    }
    

    If you wish to use a custom distribution that is not available in rand::distributions, you can implement it by following the source code for one of the distributions to see how to implement it yourself. Below is an example implementation for a distribution of some random symbols:

    use rand::{Rng, seq::SliceRandom};
    use rand::distributions::Distribution;
    
    struct Symbols;
    
    impl Distribution<char> for Symbols {
        fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> char {
            *b"!@#$%^&*()[]{}:;".choose(rng).unwrap() as char
        }
    }