Why mutable struct cannot be defined inside a function in Julia?
function test()
mutable struct ABC
x
y
z
a
end
end
throws error:
ERROR: LoadError: syntax: "struct" expression not at top level
But if the struct is global that is outside the function and accessed inside function, the code works fine.
Struct types must be defined at top-level (i.e. in the "module scope"), as the error suggest, and you can not define function-local structs like in your example.
If you really don't want to define the struct type in a module, then you can use a NamedTuple
, which can sometimes take the place of an "anonymous struct type". Example:
function test()
nt = (x = 1, y = 2, z = 3, a = "hello")
# ...
end