Default RNG in struct


I want to create a struct that will randomly generate some numbers. I want to have the possibility to set the random number generator or use a default rng if not specified. The api should look like this.

let generator = Generator::new(...);
let random_number = generator.generate();

let mut other_generator = Generator::new(...);
other_generator.set_rng(a given rng);
let other_random_number = other_generator.generate();

I've tried to implement Generator using an option, but the type inference is not working. Do you have any idea on how to implement such thing?

Why not Generator::new() -> Generator<DefaultRng> and Generator::with_rng<R>(R) -> Generator<R>? Do you need the ability to change the RNG after creation?

You can also do Builder pattern, by making with_rng take self, changing Generator<R1> into Generator<R2>.

let gen = Generator::new()
1 Like

Indeed I would like to be able to mutate the generator later. The builder pattern is not a bad idea.