Help with defining macros

I have a struct as follows:

@kwdef struct Node
    index
    value
    optional_attribute = 0.0
end

@kwdef struct Network
    nodes::Vector{node} = Node[]
end

Now, I can define a Network object and assign nodes to it. However, I want to do it a bit differently using macros. Something like:

#Initialize a network
V = Network()

#Now fill in the nodes using macro
@node(V,  1, 10) #index=1, value=2
@node(V, 2,  20, optional_attribute=5)
#and so on

How do I define this macro @node. Also, since node belongs to V, I should be later able to retrieve it using V.nodes. This is probably a trivial question but I have never used macros before hence the question. Any help is appreciated. Thank you.

Why would you want to use a macro? The job of macros is to transform expressions before run time.

A function will do the trick.

node!(V::Network, i,v; kwargs...) = push!(V.nodes, Node(;(index=i,value=v,kwargs...)...))
1 Like

I guess you’re right. Your function would do the trick and macro is probably overkill here. I am just learning about macros and was trying to give it a shot here. Is it possible at all here? If yes, how would you do that? (I understand this is a bad use case though as you said)

Thanks.

Mandatory link:

1 Like

Haha. OK. Thanks for the link :sweat_smile: