Static variable in a templated function or struct

There are a lot of discussions to emulate local static variable in Julia. One is to use let block,

       let a = 0
           global function f()
               a += 1
           end
       end

However, it is not working in a template function or struct. The following example shows what I need

    struct Foo{DIM}
        function Foo{DIM}() where {DIM}
            static x=Vector{Int64}(undef,DIM)
            # initialization of static variable when it is first called
        end
    end

The static variable is a large array, and the value depends on the parametric type T. The initialization of the static variable is also time consuming. Therefore, it is better shared between all instances.

Is there a way to implement it in Julia?

Writing to static variables won’t be thread safe, which is why people generally prefer alternatives like explicitly passing around preallocated memory/objects, or maybe get!ing them from the task local storage.

One trick you could do though is

@generated function foo(x::T) where {T}
    staticvar = ...
    quote
        sv = $staticvar
        ...
    end
end
3 Likes