```
mutable struct DistrRng{T<:Sampleable}
d::T
rng::MersenneTwister
function DistrRng(d::T, rng::MersenneTwister) where T <: Sampleable
return new{T}(d, deepcopy(rng))
end
function DistrRng(d::T; seed::Int = nullIndex) where T <: Sampleable
rng = (seed >= 0 ? MersenneTwister(seed) : MersenneTwister(rand(UInt32)))
return new{T}(d, rng)
end
end
global GlobalRngBackup = MersenneTwister(0);
function copyRng!(dest::MersenneTwister, src::MersenneTwister)
dest.seed = src.seed
dest.state = src.state
dest.vals = src.vals
dest.ints = src.ints
dest.idxF = src.idxF
dest.idxI = src.idxI
end
function Base.rand(distrRng::DistrRng, n::Int)
rng = distrRng.rng # shorthand
copyRng!(GlobalRngBackup, GLOBAL_RNG)
copyRng!(GLOBAL_RNG, rng)
value = rand(distrRng.d, n)
copyRng!(rng, GLOBAL_RNG)
copyRng!(GLOBAL_RNG, GlobalRngBackup)
return value
end
function Base.rand(distrRng::DistrRng)
return rand(distrRng, 1)[1]
end
```

The above is a very interesting piece of code to randomly generate a number following a given probability distribution sampler and random number generator, with the help of rewriting the default `Base.rand`

functions. I only have a few confusing points as the following.

1: In the first inner constructor inside of the `mutable struct DistrRng`

, `deepcopy`

is used. Then, in the function `copyRng!`

, apparently, a simple reassignment is used. I was wondering, why is this?

2: Is there a better way to accomplish this, besides rewriting this `Base.rand()`

function?