Creating symbols inside of macros

How to create symbols (and new types) inside of macros?

macro mymacro(arg)
  quote
    structname = Symbol($arg,"ext")
    struct structname
    end
  end
end

In this example, I am expecting a call @mymacro "Foo" to define a new struct type Fooext.

I’m on my phone now, so I cannot test things. But @macroexpand is your friend to test things out. Try escaping your quote: esc(quote ... end).
This would be my guess

macro mymacro(arg)
    structname = Symbol($arg,"ext")
    esc(quote
      struct $structname
      end
  end)
end
1 Like

Hi @favba, I think the issue is somewhere else, aren’t macros supposed to return quotes?

No. Macros are supposed to return an expression based on the inputs (expressions) it gets. Most macros won’t just be a quote, there will be code outside it and not all of the processing will be done in the quote.

@favba is totally correct here though a slightly more preferred version would be

macro mymacro(arg)
    quote
        struct $(esc(Symbol(arg, "ext"))) # This is spliced inside the quote, you can of course hoist it into `structname` **OUTSIDE** the quote as in @favba's answer.
        end
    end
end
3 Likes