The rng
crate is neither Sync
nor Send
, so the rng::thread_rng can not cross the .await point. What is the simplest and beautiful way to generate random numbers in async rust?
Generating A lot of numbers beforehead and then use them is ugly.
The rng
crate is neither Sync
nor Send
, so the rng::thread_rng can not cross the .await point. What is the simplest and beautiful way to generate random numbers in async rust?
Generating A lot of numbers beforehead and then use them is ugly.
From the tokio Discord
let random = rand::random::<i64>();
or
let random = {
let mut rng = rand::thread_rng();
rng.gen::<i64>()
}
"make sure the rng variable falls out of scope before you use an await"
Getting a new rng handle is cheap. A rng will be created once per thread (when used), and after that ThreadRng::default
only uses LocalKey::with and Rc::clone. Do you need to keep the previous state so the number sequence is repeatable?