smol-rs / fastrand

A simple and fast random number generator
Apache License 2.0
408 stars 35 forks source link

Rng::with_seed doesn't affect the thread-local Rng #45

Closed malachid closed 1 year ago

malachid commented 1 year ago

If you create a seeded generator using:

fastrand::seed(num)
println!("{}", fastrand::u8(0..50));

the value will be reproducible with each run.

If you instead do:

fastrand::Rng::with_seed(num)
println!("{}", fastrand::u8(0..50));

the value will be different on every run.

I believe the intention is that setting a seed would make runs reproducible.

taiki-e commented 1 year ago

I.e., in the second example, the seed is not actually changed.

taiki-e commented 1 year ago

Closing as it is working as intended (Rng::with_seed doesn't affect the thread-local Rng). Once https://github.com/smol-rs/fastrand/pull/46 is merged, the compiler will show a useful warning in such cases.

warning: unused return value of `Rng::with_seed` that must be used
  --> tests/smoke.rs:35:5
   |
35 |     fastrand::Rng::with_seed(1);
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |
   = note: this creates a new instance of `Rng`; if you want to initialize the thread-local generator, use `fastrand::seed()` instead
malachid commented 1 year ago

Thanks for the quick clarification!