In C, one can declare static variables with local function scope (example).
Can something similar be done in Julia?
My use case is declaring sub-functions, but do not want Julia to have to reparse them every time the code executes. Declaring them outside of the function is ugly and gives them higher scope, which I want to avoid.
example:
function foo(x)
static bar = t -> stuff with t
...
bar(y)
...
end
While I could declare bar() outside of foo(), I would prefer bar to only be in the local namespace.
Thank you.
You can create a new scope around the function, to hold the variable.
let
global foo
function bar(t)
#stuff with t
end
y = 2
function foo(x)
#...
bar(y)
#...
end
end
Then only foo(x)
will be visible to the outside
Based on @ivarne's answer.
let bar = t -> t^2
global foo
function foo(x)
bar(x)
end
end
But I don't think this is an ideal solution. IMHO it would be better to have a static
keyword. The extra block is unwieldy. There is some discussion about this in Julia development:
https://github.com/JuliaLang/julia/issues/15056
https://github.com/JuliaLang/julia/issues/12627
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With