logo

Checking Struct Properties in Julia 📂Julia

Checking Struct Properties in Julia

Code

propertynames()

You can check with the propertynames() function1. Since Julia has no classes, only structs2, all symbols returned by this function are precisely the names of properties only.

The following is code for creating an Erdős–Rényi network in the Graphs package, checking the number of nodes, and each node’s neighborhood. The propertynames() function was used on this network, and :ne and fadjlist properties were returned as symbols.

julia> using Graphs

julia> G_nm = erdos_renyi(50,200)
{50, 200} undirected simple Int64 graph

julia> propertynames(G_nm)
(:ne, :fadjlist)

julia> G_nm.ne
200

julia> G_nm.fadjlist
50-element Vector{Vector{Int64}}:
 [3, 4, 11, 25, 26, 27, 33, 40, 44, 48]
 [11, 17, 20, 23, 24, 38, 45, 50]
 [1, 4, 15, 24, 29, 30, 34, 42, 46]
 [1, 3, 18, 24, 30, 32, 43, 45]
 [6, 7, 8, 24, 26, 29, 37, 39, 50]
 ⋮
 [3, 13, 17, 28, 29, 32, 39, 44, 47, 49]
 [10, 14, 18, 26, 32, 36, 41, 44, 46]
 [1, 21, 23, 24, 25, 32, 41, 44, 45]
 [9, 13, 14, 17, 21, 31, 43, 46, 50]
 [2, 5, 13, 28, 31, 32, 35, 42, 44, 49]

fieldnames()

This is a bit of a more complicated story, but not knowing it doesn’t really impact Julia programming.

Fundamentally, propertynames(x) is the same as fieldnames(typeof(x))3. Although not very significant as a function in practical use, the fact we can learn from this is that in Julia, the instance of a structure is called an object, the attributes a structure itself possesses are called fields, and the properties of an object existing as an instance are called properties.

Environment

  • OS: Windows
  • julia: v1.6.0