Implementing singletons for configuration variables

Your solution looks reasonable to me, except that redefining the constructor is very hackish (and do you need the struct the be mutable?).

You can instead check if the variable s is defined:

module Settings
    struct SettingsStruct
        a::Int64
        b::Int64
        function SettingsStruct(a, b)
            isdefined(Settings, :s) && error("Cannot instantiate SettingsStruct twice")
            return new(a, b)
        end
    end

    const s = SettingsStruct(2, 3)
end

See also Implementing Singleton design pattern.

However in this case I would just use a const with no additional check: you already get a warning if you change it:

WARNING: redefinition of constant s. This may fail, cause incorrect answers, or produce other errors.

But yeah, I do wish it would give an error instead. The current behavior seems designed for playing around and prototyping rather than building robust applications.

This was recently discussed on Behavior of reassignment to a `const` · Issue #38584 · JuliaLang/julia · GitHub.

2 Likes