AntonOresten / DynamicStructs.jl

Structs and dictionaries had a baby
MIT License
3 stars 1 forks source link

DynamicStructs

Latest Release Build Status Coverage

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.

Usage

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

Features

julia> (isdynamictype(Spaceship), isdynamic(ship), isdynamic(Spaceship))
(true, true, false)
julia> getproperties(ship; fields=false)
(:crew,)
julia> ship
Spaceship:
  1 field:
    name::String = "Hail Mary"
  1 property:
    crew::Vector{String} = ["Grace"]

See also