How do I define a structure inside a function?

Hello,
I want to define a structure inside a function:

function PrintDate(d::Date)
    struct Date 
        day::Int64
        month::String
        year::Int64
    end
    println(d.day,d.month,d.year)
end

chmas = Date(25,"Dec",2025)

PrintDate(chmas)

But I got the following error:

ERROR: LoadError: syntax: "struct" expression not at top level

How to solve it?

Thank you.

I have never seen a structure defined inside a function. Is there a reason why you don’t want to define it outside?

1 Like

Why not define the structure outside of the function?

julia> struct Date 
           day::Int64
           month::String
           year::Int64
       end

julia> function PrintDate(d::Date)
       println(d.day,d.month,d.year)
       end
PrintDate (generic function
 with 1 method)

julia> chmas = Date(25,"Dec",2025)
Date(25, "Dec", 2025)

julia> PrintDate(chmas)
25Dec2025

If you want to create structures on the fly, consider using named tuples

julia> chmas = (day=25,month="Dec",year=2025)
(day = 25, month = "Dec", year = 2025)


julia> function PrintDate(d)
       println(d.day,d.month,d.year)
       end
PrintDate (generic function with 2 methods)

julia> PrintDate(chmas)
25Dec2025
5 Likes

Hello,
Thank you for your answers.
So, is this impossible?

Yes. It’s says so. “not at top level”. You can however run top level stuff inside a function with eval or @eval:

function f()
    @eval struct Foo
        a::Int
    end
end

and even create it with you own name

function g(name)
    @eval struct $(Symbol(name))
        a::Int
    end
end
g("MyStruct")
3 Likes

The question sounds like an XY problem.

I suspect that you are trying to solve a specific problem, for which defining a structure in a function seemed like a good solution. If you share the original problem here, you are likely going to get much better suggestions.

10 Likes

Hello,
I’m learning Julia and here I’ll ask questions that come to my mind.

2 Likes

Of course any questions are welcome. What @barucden meant to say is that, from the perspective of people who have been using Julia for a while, if you feel like you need to define a struct inside a function, you may need to rethink your approach.

11 Likes

In particular, most use cases for a struct defined in a function are covered either by named tuples, as mentioned, or parametric types.

3 Likes