I would like to able to define a static variable inside a Julia struct. E.g I would like to define something along the lines of:
mutable struct MyStruct
  global const a = 1
  b = 2
end
Then I would like to be able to access a, in a similar fashion to static constants in the Java or C++ languages, e.g:
MyStruct.a
I am very well aware that this way of writing code is not-Julian, and that I just could use a module for this purpose.
However, I am interested in whether it is possible or not for mutable structs. E.g I am interested in in details why this is not possible and techniques to emulate this pattern of programming.
(edit since you asked for something that does not require an instance of the struct)
Another way to do this is:
julia> mutable struct MyStruct b::Int end
julia> a(::Type{MyStruct}) = 1
a (generic function with 1 method)
julia> a(MyStruct)
1
which is accessed as a(Mystruct) instead of MyStruct.a
============================================================ (first answer):
You will need one more struct, and the syntax would be x.a.a not x.a:
julia> struct A
   a::Int
   end
julia> A() = A(1)
A
julia> s = A()
A(1)
julia> s.a
1
julia> mutable struct MyStruct
   a::A
   b::Int
   end
julia> MyStruct(b) = MyStruct(A(), b)
MyStruct
julia> c = MyStruct(3)
MyStruct(A(1), 3)
julia> c.a.a
1
julia> c.a.a = 5
ERROR: type A is immutable
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With