DynamicStructs is a Julia package that allows you to create structs with dynamic properties. These properties behave similarly to fields of type Any
in mutable structs, but are bound to the instance rather than the type, and can be added and deleted at runtime.
Install from the REPL with ]add DynamicStructs
.
using DynamicStructs
@dynamic struct Spaceship
name::String
end
ship = Spaceship("Hail Mary", crew=["Grace", "Yao", "Ilyukhina"])
ship.name # "Hail Mary"
ship.crew # ["Grace", "Yao", "Ilyukhina"]
ship.crew = ["Grace"] # reassign crew
ship.fuel = 20906.0 # assign fuel
ship.crew # ["Grace"]
ship.fuel # 20906.0
hasproperty(ship, :fuel) # true
delete!(ship, :fuel) # delete fuel
hasproperty(ship, :fuel) # false
ship.fuel # ERROR: Spaceship instance has no field or property fuel
@dynamic
macro.mutable struct
to allow for modifying field values.isdynamictype
and isdynamic
:julia> (isdynamictype(Spaceship), isdynamic(ship), isdynamic(Spaceship))
(true, true, false)
getproperties(ship; fields=false)
:julia> getproperties(ship; fields=false)
(:crew,)
show_fields_properties(io, x)
):julia> ship
Spaceship:
1 field:
name::String = "Hail Mary"
1 property:
crew::Vector{String} = ["Grace"]