struct with evaluated/calculated attributes in Julia

Viewed 158

I am incredibly new to Julia, as in I downloaded it yesterday. I need to use structs for a project I am trying to start. I need my objects to consist of attributes that are part of the input and attributes that are calculated from that input. For example, I tried:

struct Bar
    #Attributes from input
    E::Float64
    A::Float64
    L::Float64

    # Attributes calculated form input
    k = (E*A/L)*[1.0 -1.0; -1.0 1.0]
end

but I get an error:

ERROR: LoadError: syntax: "k = (((E * A) / L) * [1 -1; -1 1])" inside type definition is reserved around Untitled-1:10

How should I go about achieving my desired outcome?

2 Answers

You don't need any special package or macro to do this. Just do it the standard way, in the constructor. The last struct attribute isn't some sort of special 'evaluated attribute', it's a completely ordinary attribute.

 struct Bar
    E::Float64
    A::Float64
    L::Float64
    k::Matrix{Float64}
 end
 Bar(e, a, l) = Bar(e, a, l, (e*a/l)*[1 -1; -1 1])
 
 jl> Bar(2,3,4)
 Bar(2.0, 3.0, 4.0, [1.5 -1.5; -1.5 1.5])

You can try:

Base.@kwdef struct Bar                                                                                                    
    E::Float64                                                             
    A::Float64                                                             
    L::Float64                                                             
    k::Matrix{Float64} = (E*A/L) .* [1.0 -1.0; -1.0 1.0]                   
end                                                                        

and now:

julia> Bar(;E=1,A=2,L=3)
Bar(1.0, 2.0, 3.0, [0.6666666666666666 -0.6666666666666666; -0.6666666666666666 0.6666666666666666])

Important notes:

  • always define field type if possible - even when you set the default value for it
  • instead of Base.@kwdef you could try using Parameters package and the Parameters.@with_kw macro which is more powerful and has more options.
Related