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
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
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.
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.