# \`consttype\` keyword

**URL:** <https://discourse.julialang.org/t/consttype-keyword/27497>\
**Category:** Internals & Design\
**Created:** [August 13, 2019, 12:01pm UTC](https://discourse.julialang.org/t/consttype-keyword/27497 "2019-08-13T12:01:50Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![gdkrmr](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/gdkrmr/32/2791_2.png) [@gdkrmr](https://discourse.julialang.org/u/gdkrmr)\
**Post date:** [August 13, 2019, 12:01pm UTC](https://discourse.julialang.org/t/consttype-keyword/27497/1 "2019-08-13T12:01:50Z")

</div>

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

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

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

---

<div class="post-metadata">

**Author:** ![dfdx](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/dfdx/32/120_2.png) [@dfdx](https://discourse.julialang.org/u/dfdx)\
**Post date:** [August 13, 2019, 12:17pm UTC](https://discourse.julialang.org/t/consttype-keyword/27497/2 "2019-08-13T12:17:30Z")

</div>

You can achieve similar behavior using `Ref{T}`:

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

julia> x[]
1

julia> x[] = 2
2

julia> x[]
2

```

---

<div class="post-metadata">

**Author:** ![stevengj](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevengj/32/71_2.png) [@stevengj](https://discourse.julialang.org/u/stevengj)\
**Post date:** [August 13, 2019, 12:33pm UTC](https://discourse.julialang.org/t/consttype-keyword/27497/3 "2019-08-13T12:33:35Z")

</div>

> [@gdkrmr](#):
>
> Has this ever been proposed?

> <https://github.com/JuliaLang/julia/issues/964>
>
> Is it expected behaviour that I can't type annotate variable declarations in glo…bal scope? Example:
> 
> \`\`\` julia
> julia\> foo::Float = 0.1
> foo not defined
> 
> julia\> function bar()
> foo::Float = 0.1
> end
> 
> julia\> bar()
> 0.1
> \`\`\`
