Static structs with constant field

Hey guys,

It’s there a way to declare a constant struct.

const struct A
    a = 1
    b = "value"
end

println(A.b)

Thy for your time

I’m not exactly sure I understand what you’re asking, but it looks like you’re mixing the definition of a struct with the construction of an instance of that struct.

I think what you want to do is this:

struct MyStruct
    a::Int
    b::String
end

const A = MyStruct(1, "value")

at the repl we see

julia> println(A.b)
value

Another thing you could do is use a NamedTuple, they’re a big like ‘anonymous structs’, e.g.

julia> const A = (;a=1, b="value")
(a = 1, b = "value")

julia> println(A.b)
value
4 Likes

I think what OP is looking for is more along the lines of static variables in OOP classes (shared value among all instances of the class). Julia doesn’t have these, but the typical way to get the same effect in Julia is to just use a global variable.

1 Like

I like the NamedTuple. Didn’t think of that, but it’s basically what I need