I need a macro that generates accessor functions in the Julia programming language. With a struct like this:
struct Account
account_number::String
balance::Float64
end
I want it to generate this code:
account_number(acc::Account) = acc.account_number
balance(acc::Account) = acc.balance
And I want to use it like so:
@generate_accessors Account
I have searched the internet and found the Accessors.jl package, but it does not seem to be related to my issue. There is quite a Julia community so I hope a macro like this exists somewhere. Unfortunately I do not have enough Julia experience to implement such a macro myself, I don't even know if such a macro can be made at all. Thanks for any help of pushes in the right direction.
I do not know of a library that has such a macro but creating a basic one is not too difficult:
# accessor(:foo, FooBar) -> quote foo(x::FooBar) = x.foo end
accessor(field, type) = :($(esc(field))(x::$type) = x.$field)
macro generate_accessors(type)
definitions = (accessor(s, type) for s in fieldnames(eval(type)))
Expr(:block, definitions...)
end
julia> struct FooBar
foo
bar
end
julia> @generate_accessors FooBar
bar (generic function with 1 method)
julia> foo(FooBar(1,2))
1
julia> bar(FooBar(1,2))
2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With