This is a follow-up of this thread, which ended with this new issue I am not sure how to solve:
The issue is the following: The usage of my package starts with the user defining a series of options which are organized in a struct. Now I want to add to that struct
the possibility of the user defining which is the random number generator to be used. I am using Parameters
, so I have default options:
using Parameters
@with_kw struct Options
# ... other fields
seed :: Int64 = 321
rng = Random.MersenneTwister(seed)
end
The problem with this is that, the user will initialize these options with, in the simplest case:
opt = Options()
which leads to the situation that using rand(rng)
allocates memory:
julia> @allocated rand(opt.rng)
31353
julia> @allocated rand(opt.rng)
48
If the opt
instance was constant, the allocations go away:
julia> const opt2 = Options()
Options
seed: Int64 321
rng: Random.MersenneTwister
julia> @allocated(opt2.rng)
0
I do not want to impose to the user the use const opt = ....
, this would be quite cumbersome, because then he/she would have to change the variable name every time in a script to run the package with different options.*
I am unsure how to proceed here. I need rng
to be a constant, but which can be optionally defined and yet having a default value if nothing is defined by the user. It does not need to be a part of the Options
structure, it can be a global variable (changing its value will be a very rare situation, actually only during package testing).
I ended up with the idea that I could pass a parameter for the module during loading, but that feature was not implemented because it seems that better solutions were found every time.
*Telling the user to wrap everything inside a let
block, or a function, is also not an option here. Everything computationally demanding in this package is done by other function which receives those options as a parameter, and that is perfectly fine, fast, with no allocations, except now for the necessity of giving the user the option to change the random number generator.