Vinod
Vinod

Reputation: 4352

Why mutable struct cannot be defined inside a function in Julia

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.

Upvotes: 5

Views: 684

Answers (2)

Przemyslaw Szufel
Przemyslaw Szufel

Reputation: 42214

You could use meta-programming. Strongly not recommended unless you very exactly know that you want and need to use meta-programming.

function test()
    Main.eval(
        quote
           mutable struct ABC
               x
               y
               z
               a
           end
        end
    )
end

Testing:

julia> test()

julia> fieldnames(ABC)
(:x, :y, :z, :a)

Upvotes: 2

fredrikekre
fredrikekre

Reputation: 10984

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

Upvotes: 7

Related Questions