generate a random string in rust

To generate a random string in Rust, you can use the rand crate, which provides several methods to generate random numbers and values. Here is an example code snippet that generates a random string of length 10:

main.rs
use rand::Rng;

fn generate_random_string(length: usize) -> String {
    let mut rng = rand::thread_rng();
    let mut result = String::with_capacity(length);
    for _ in 0..length {
        let random_char = (rng.gen_range(b'a', b'z' + 1)) as char;
        result.push(random_char);
    }
    result
}

fn main() {
    let random_string = generate_random_string(10);
    println!("Random string generated: {}", random_string);
}
431 chars
17 lines

In this code snippet, we first import the Rng trait from the rand crate. We then define our generate_random_string function that takes a length parameter of type usize and returns a String.

Inside the function, we create a thread_rng instance of rand::prelude::ThreadRng, which we'll use to generate random values. We also create an empty String variable called result with length capacity.

Finally, we loop over length times and in each iteration, we generate a random character using rng.gen_range(b'a', b'z' + 1)) as char, which generates a random number in the range of ASCII values for lowercase letters (97 to 122) and converts it to a char. We then append the random character to our result string using result.push(random_char).

Once the loop is complete, we return the resulting String. Note that this implementation only generates lowercase alphabetical characters. You can modify the implementation to include uppercase letters, digits or other characters if needed.

gistlibby LogSnag