How to generate a random byte array in Rust 2018?
1 min readDec 8, 2018
It’s very simple (but not documented) for byte arrays of 1 to 32 elements:
use rand::Rng;
fn main() {
let random_bytes = rand::thread_rng().gen::<[u8; 32]>();
println!("{:?}", random_bytes);
}
If you need more than 32 random bytes than this is one way to do it (although I am not sure if it’s optimal):
use rand::Rng;
fn main() {
let random_bytes: Vec<u8> = (0..1024).map(|_| { rand::random::<u8>() }).collect();
println!("{:?}", random_bytes);
}