# Define a static type variable is too Verbose

**URL:** <https://discourse.julialang.org/t/define-a-static-type-variable-is-too-verbose/22779>\
**Category:** General Usage\
**Created:** [April 5, 2019, 3:15am UTC](https://discourse.julialang.org/t/define-a-static-type-variable-is-too-verbose/22779 "2019-04-05T03:15:25Z")\
**Posts on this page:** 1\
**Showing post:** 8

<div class="post-metadata">

**Author:** ![juthohaegeman](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/juthohaegeman/32/8620_2.png) [@juthohaegeman](https://discourse.julialang.org/u/juthohaegeman)\
**Post date:** [April 5, 2019, 8:25am UTC](https://discourse.julialang.org/t/define-a-static-type-variable-is-too-verbose/22779/8 "2019-04-05T08:25:45Z")

</div>

> [@c42f](#):
>
> A more ergonomic and less intrusive version of such a macro could be written which applies the above rules to all assignments within a function (hah, we could call it `@typestable` ) but it would need to understand julia’s variable scoping rules.

I think doing it at the time when the variable was defined, like initially requested, is the easy solution:

```julia
"""
    @var x = rhs

Define `x` to be of fixed type, the type of `rhs`, and assign `rhs` to it.
"""
macro var(ex)
    if !(ex isa Expr && ex.head == :(=))
        throw(ArgumentError("expression should be of the form `var = value`"))
    end
    name = ex.args[1]
    rhs = ex.args[2]
    tmp = gensym(name)
    esc(quote
        $tmp = $rhs
        ($name)::typeof($tmp) = $tmp
    end)
end

```

Test

```julia
julia> function f(x)
           @var y = x
           y = 1.2
           return y
           end
f (generic function with 1 method)

julia> f(1)
ERROR: InexactError: Int64(1.2)
Stacktrace:
 [1] Type at ./float.jl:703 [inlined]
 [2] convert(::Type{Int64}, ::Float64) at ./number.jl:7
 [3] f(::Int64) at ./REPL[2]:3
 [4] top-level scope at REPL[3]:1

julia> f(1.3)
1.2

```

---

_[View the full topic](https://discourse.julialang.org/t/define-a-static-type-variable-is-too-verbose/22779)._
