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

Hi you could add intern constructor:
const struct A
a
b
A=new(1,“value”)
end

This causes the fields to be constant. They can’t be changed. It seems to me a way to group constant values. Is this correct?

  1. Why are you answering a topic of four ago?
  2. Why const struct? struct without mutable in front of it is already immutable by default.
  3. A=new(1,“value”), I think you meant A()=new(1,“value”)
  1. Just starting Julia. Was looking for how to make code more clear without documentation.
  2. Right but when you define constructor without parameters, even when defining a variable of the A type. values for a and b component will always be 1 and “value”. Since constructor is interally defined. i.e bad=A(2,“bad”) will give error. I saw there was a macro @kwdef. When you define here all fields you get same effect.```
    @kwdef struct A
    a=1
    b=“value”
    end
In fact you get a type which contains a singleton.
3. You are right about A() error. It should be A()=new(1,"value")