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

**URL:** <https://discourse.julialang.org/t/how-to-correctly-define-and-use-global-variables-in-the-module-in-julia/65720>\
**Category:** General Usage\
**Created:** [August 3, 2021, 5:46am UTC](https://discourse.julialang.org/t/how-to-correctly-define-and-use-global-variables-in-the-module-in-julia/65720 "2021-08-03T05:46:29Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![aramirezreyes](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/aramirezreyes/32/42573_2.png) [@aramirezreyes](https://discourse.julialang.org/u/aramirezreyes)\
**Post date:** [August 3, 2021, 6:43am UTC](https://discourse.julialang.org/t/how-to-correctly-define-and-use-global-variables-in-the-module-in-julia/65720/2 "2021-08-03T06:43:27Z")

</div>

Hi CRquantum! And welcome to the Julia discourse!

[Having global variables is not considered the best practice](https://docs.julialang.org/en/v1/manual/performance-tips/#Avoid-global-variables) 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](https://docs.julialang.org/en/v1/base/c/#Core.Ref):

```julia
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](https://docs.julialang.org/en/v1/base/base/#global).

And it doesn’t accept values of other types:

```julia
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

```

---

_[View the full topic](https://discourse.julialang.org/t/how-to-correctly-define-and-use-global-variables-in-the-module-in-julia/65720)._
