Let’s say I want to define a static-type variable inside a function,
the data structure is very complex, it is a Vector, containing a Pair, with String => Matrix
Once defined, I want the Type to be stable and never change.
function test1()
complexobj = Vector{Pair{String, Matrix{Float64}}}()
# do some work...
complexobj = 1 # This is ok! complexobj will be "Any", Not good
return complexobj
end
Test1 is bad, If I accidentally re-define complexobj, the program will NOT alert me.
function test2_wont_compile()
complexobj::Vector{Pair{String, Matrix{Float64}}} = Vector{Pair{String, Matrix{Float64}}}()
# do some work...
complexobj = 1 # This will fail
return complexobj
end
Test2 is exactly what I want! and It is usually the same logic as C++/C#/Java, Once I define complexobj 's type, If I accidentally re-define it, complier give me an error.
That is what I want already.
However, this is extremely Verbose, No? I have to write the Type (very long sentence) 2 times!
In C# or Java script, I guess I can replace the first Type sentence by “var”
e.g. If Julia could have something like this and act same as test2, it will be great:
function test3()
var complexobj = Vector{Pair{String, Matrix{Float64}}}()
# do some work...
complexobj = 1 # This should also Fail
return complexobj
end
Or, why I cannot define a const inside a function? this one failed:
function test4()
const complexobj = Vector{Pair{String, Matrix{Float64}}}()
# do some work...
complexobj = 1 # This should also Fail
return complexobj
end
Alternatively, I can create a “Struct” to store this complicated data structure.
However, I have many places such complicated structure and each time the data structure is different.
Each time, I will have a “ad-hoc” task and each time the complicated data structure is different
e.g. one day I may want a
Dict{String, Vector{Vector{}}}
another day I want to do something like:
Pair{String, Vector}
maybe another day, I want to have something like:
Vector{Pair{ MyCustomStruct, Vector{MyCustomStruct}}
etc etc.
My job are very adhoc that each day I may have a new task with new diff requirement. So each time I need to have a new data structure (usually quite complicated)
So I need to stay very flexible (instead of creating a generic “struct”)
Is there a way to reduce the Verbose of
complexobj::Vector{Pair{String, Matrix{Float64}}} = Vector{Pair{String, Matrix{Float64}}}()
But still can make sure once complexobj type is defined, it will never change, like test2?
Thank you