Why mutable struct cannot be defined inside a function in Julia
Asked Answered
W

2

5

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.

Wordplay answered 24/1, 2022 at 7:22 Comment(3)
The question is: what is it that you want to do in the end? If you know the field names x, y, z, a beforehand, there's no need to define the struct within the function in the first place. And then, what should the function return? A type? An instance?Conciliator
@Conciliator I want to create multiple instances of struct. Function uses struct. Function does not return struct.Wordplay
@Wordplay I think you are confusing a type with instances of a type. A struct block does not create instances of a type, it defines the type itself. It is similar to the difference between a class and an object of a class in OOP languages.Kilmarx
H
7

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
Holothurian answered 24/1, 2022 at 8:21 Comment(3)
And Dict can work like kind-of mutable struct.Lizettelizotte
Actually I want to make many instances of struct. Can it be done with NamedTuple?Wordplay
The standard way is to just define the struct outside the function, what is wrong with doing that? Yes, you can create as many tuples/dicts as you want.Holothurian
S
2

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)
Stheno answered 24/1, 2022 at 9:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.