Hi,
I’m trying to convert all package global variables to const global, but some of them must be reset at the end (their state is checked at some code point).
As an example
julia> a = Array{GMT.GMTcpt,1}(undef,1)
1-element Array{GMT.GMTcpt,1}:
#undef
julia> a[1] = makecpt(range=(0,11,1));
julia> typeof(a[1])
GMT.GMTcpt
So far so good, but at the end of the usage loop I need to reset the variable to its initial #undef state. Tried a couple variations around this but no success
julia> a[1] = Core.undef
ERROR: MethodError: Cannot `convert` an object of type UndefInitializer to an object of type GMT.GMTcpt
Closest candidates are:
convert(::Type{T}, ::T) where T at essentials.jl:168
GMT.GMTcpt(::Any, ::Any, ::Any, ::Any, ::Any, ::Any, ::Any, ::Any, ::Any, ::Any) at C:\Users\joaqu\.julia\dev\GMT\src\gmt_main.jl:45
Stacktrace:
[1] setindex!(::Array{GMT.GMTcpt,1}, ::UndefInitializer, ::Int64) at .\array.jl:782
[2] top-level scope at REPL[20]:1
Is this resetting possible to do?
This seems a very strange way of coding. However, you can transform you vector to also hold Nothing
and, when checking for undef
, you can also check for nothing
:
julia> mutable struct A
a::Int
end
julia> v = Vector{Union{A,Nothing}}(undef,10)
10-element Array{Union{Nothing, A},1}:
#undef
#undef
#undef
#undef
#undef
#undef
#undef
#undef
#undef
#undef
julia> v[1] = A(1)
A(1)
julia> v
10-element Array{Union{Nothing, A},1}:
A(1)
#undef
#undef
#undef
#undef
#undef
#undef
#undef
#undef
#undef
julia> v[1] = nothing
julia> v
10-element Array{Union{Nothing, A},1}:
nothing
#undef
#undef
#undef
#undef
#undef
#undef
#undef
#undef
#undef
1 Like
Yes, it’s something around these lines that I’m considering
julia> a = Array{Any,1}(undef,1)
1-element Array{Any,1}:
#undef
julia> a[1] = nothing
julia> a[1] = makecpt(range=(0,11,1));
julia> a[1] === nothing
false
...
julia> a[1] = nothing
julia> a[1] === nothing
true
What is it that you find so strange? To use const global var and still be able to change var I can change only the contents of var but not its bindings. And at the end I need to reset the contents of var.
Using Array{Any}
and things like that you will loose a lot of performance. What are you actually trying to accomplish?
I know, but globals are not performant either (though those in question are not used often). What I’m trying to avoid is the doing this
that later may be changed to this
but that at the end must become again = nothing
I think what you are trying to do is implemented in the excellent package OptionalData.jl created by @helgee
1 Like