`consttype` keyword

Has this ever been proposed? What about adding a consttype keyword, that forces a value to have a certain type:

julia> consttype x = 3
3

julia> x = 1.5
Error: x must be of type Int

# alternatively convert as in array assignment:

julia> x = 1.5
InexactError ...

This could make a lot of global code faster and help to avoid possible typeinstabilities in functions. E.g.

function f()
  consttype x = 1
  for i in 1:1000
    x += rand()
  end
  return x
end

could throw an error instead of silently having bad performance.

You can achieve similar behavior using Ref{T}:

julia> const x = Ref(1)
Base.RefValue{Int64}(1)

julia> x[]
1

julia> x[] = 2
2

julia> x[]
2
2 Likes