I think the problem is that the âperformance tipsâ section of the manual tells people to declare global variables as const or they will be slow. When people then discover that the value of a const can be changed, they figure that theyâve found a way to have fast globals.
Better documentation might help, but a much cooler solution would be if constants were treated as inlined functions, so that redefining a constant triggers re-compilation of every function where it is used. (I donât care if this is slow. Just add another performance tip saying âavoid redefining constantsâ.)
What is a good use case for global variables? Is there an argument that can be made for their inevitability?
Or, can global variables be avoided altogether?
Note that const only affects the variable binding; the variable may be bound to a mutable object (such as an array), and that object may still be modified.
so eg
module T
const a = [true]
change_flag(flag::Bool) = a[1] = flag
get_flag() = a[1]
end
Yes, but they are not, strictly speaking, global variables. They behave like something halfway between a variable and a const. Compare the following examples:
a = 0
function f()
global a = 1
println(a)
end
b() = 0
function g()
global b() = 1
println(b())
end
const c = 0
function h()
global c = 1
println(c)
end
The first invocation of f() prints 1, but the first invocations of g() and h() print 0. Still, g() prints 1 the second time, while h() prints 0 every time.
If it were up to me, Iâd forbid redefining both functions and global consts from inside a function. If someone really wants to do it, he should be forced to use an eval to drop down to the global scope.
For what itâs worth, using const global containers and treating them as you would any other normal container is something I occasionally resort to, and it always seems to work just fine (perhaps the devs will have further commentary on whether this is really a smart thing to do). In my experience, there are some (rare) instances when it is simply far more convenient to associate certain variables with a module than to force users to have to juggle objects which manage them. Otherwise, Iâm not too sure why this issue keeps coming up: why would you assume that redefining something that you explicitly declared to be a const would result in ânormalâ behavior?
The value cannot be changed without a warning telling you that things shouldnât crash but can start to be inconsistent. What inconsistency you might see is only an implementation detail.
If you really need something that doesnât change type, use a global const Ref.