How to prohibit assignment to a variable in a function?

function f(x::Int)
     const  y = 5
     #some code...
     y =2 # I want this line to throw "ERROR: invalid redefinition of constant y"

Instead it throws:
ERROR: syntax: unsupported const declaration on local variable around REPL[37]:2

Short answer you can’t.
Long answer: you can’t but you shouldn’t need to.
Make your function short enough and clear enough that the logic is correct and clearly correct and it doesn’t mater.

I do think this would be a nice feature to have, or even a macro that i could annotate a function with to say that it won’t ever reassign anything.
Just because I hate it when variables are reassigned.
Probably makinga macro to detect htat is not impossible


You can always defined a named tuple in the local scope with all “constant variables” and give it a short name like c. But you probably will lose some time with errors just because you forgot to put c. before the name of a variable.

1 Like