Defstruct inside __using__`

Is it possible to define a struct inside a using

defmodule Structor do
  defmacro __using__(_) do
    quote do
      defmodule __MODULE__ do
        defstruct [:field]
      end

      def create(field) do
        %__MODULE__{field: field}
      end
    end
  end
end

defmodule MyStruct do
  use Structor

end

You don’t need the defmodule __MODULE__ do part:

defmodule Structor do
  defmacro __using__(_) do
    quote do
      defstruct [:field]

      def create(field) do
        %__MODULE__{field: field}
      end
    end
  end
end

defmodule MyStruct do
  use Structor
end

iex> MyStruct.create(:foo)
%MyStruct{field: :foo)
3 Likes

Yes, I had this originally but was was not able to get it to work because I had something else wrong. Thanks for pointing out that it should work.

1 Like