Writing our first macro

Macros are defined in a similar way to how functions are defined, except that the macro keyword is used instead of the function keyword.

We should also keep in mind that a macro must return expressions. Let's create our first macro. This macro returns an expression object that contains a for loop, as follows:

macro hello()
return :(
for i in 1:3
println("hello world")
end
)
end

Invoking the macro is as easy as calling it with the @ prefix. Refer to the following code:

Unlike functions, macros may be called without using parentheses. So we can just do the following:

Fantastic! We have now written our first macro. While it does not look very exciting, because the code being generated is just a static piece of code, we have learned how to define macros and run them.

Next, we will learn how to pass arguments to macros.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.253.152