logo

Referencing Struct Properties as Functions in Julia 📂Julia

Referencing Struct Properties as Functions in Julia

Overview

In Julia, there are mainly two ways to reference the properties of a structure. They should be used appropriately according to grammatical convenience or actual use.

Code

For example, in Julia, the // operator creates a Rational type of number as follows. The names of the properties that a rational number has include :num meaning numerator and :den meaning denominator.

julia> q = 7 // 12
7//12

julia> q |> typeof
Rational{Int64}

julia> q |> propertynames
(:num, :den)

getproperty(x, :y) and x.y

julia> getproperty(q, :den)
12

julia> q.den
12

Essentially, you just need to provide the name of the property as a symbol in the second argument of the getproperty() function. Or, as in many common programming languages, you can access the property by appending a dot after the object variable name.

Reference to Properties of Arrays

Meanwhile, the above method can be used when needed just once, but if you need to access several elements in an array, you should use broadcasting as follows. Or, if performance is not important and quick coding is needed, using list comprehension like Python is also an option.

julia> Q = [k // 12 for k in 1:12]
12-element Vector{Rational{Int64}}:
  1//12
  1//6
  1//4
  1//3
  5//12
  1//2
  7//12
  2//3
  3//4
  5//6
 11//12
  1//1

julia> getproperty.(Q, :num)
12-element Vector{Int64}:
  1
  1
  1
  1
  5
  1
  7
  2
  3
  5
 11
  1

julia> [q.num for q in Q]
12-element Vector{Int64}:
  1
  1
  1
  1
  5
  1
  7
  2
  3
  5
 11
  1

Full Code

q = 7 // 12
q |> typeof
q |> propertynames

getproperty(q, :den)
q.den

Q = [k // 12 for k in 1:12]
getproperty.(Q, :num)
[q.num for q in Q]

Environment

  • OS: Windows
  • julia: v1.9.0