How to correctly define and use global variables in the module in Julia?

Hi CRquantum! And welcome to the Julia discourse!

Having global variables is not considered the best practice because it makes code difficult to track. The other disadvantage is that unless it has a constant type it will affect your performance. But this is what I think you are trying to solve. If you still want to do this, you can use Ref:

global const var = Ref{Float64}(0.0) # Store it into a `Ref` which it's mutable but has a constant type

function f(x::Float64)
    global var[] = 2.0*x
    return nothing
end

f(2.0)

var[] #prints 4.0

You only need to write global the first time that the variable appears in a given scope and its child scopes.

And it doesn’t accept values of other types:

julia> var[] = "hola"
ERROR: MethodError: Cannot `convert` an object of type String to an object of type Float64
Closest candidates are:
  convert(::Type{T}, ::Base.TwicePrecision) where T<:Number at twiceprecision.jl:250
  convert(::Type{T}, ::AbstractChar) where T<:Number at char.jl:180
  convert(::Type{T}, ::CartesianIndex{1}) where T<:Number at multidimensional.jl:136
8 Likes