Strukt.defstruct
defstruct
, go back to Strukt module for more information.
This variant of defstruct
can accept a list of fields, just like Kernel.defstruct/1
, in which
case it simply defers to Kernel.defstruct/1
and does nothing; or it can be passed a block
containing an Ecto.Schema
definition. The resulting struct/schema is defined in the current
module scope, and will inherit attributes like @derive
, @primary_key
, etc., which are already
defined in the current scope.
Example
defmodule Passthrough do
use Strukt
defstruct [:name]
end
defmodule Person do
use Strukt
@derive [Jason.Encoder]
defstruct do
field :name, :string
end
def say_hello(%__MODULE__{name: name}), do: "Hello #{name}!"
end
Above, even though Strukt.defstruct/1
is in scope, it simply passes through the list of fields
to Kernel.defstruct/1
, as without a proper schema, there isn't much useful we can do. This allows
intermixing uses of defstruct/1
in the same scope without conflict.
This variant of defstruct
takes a module name and block containing a struct schema and
any other module contents desired, and defines a new module with that name, generating
a struct just like Strukt.defstruct/1
.
Example
use Strukt
defstruct Person do
@derive [Jason.Encoder]
field :name, :string
def say_hello(%__MODULE__{name: name}), do: "Hello #{name}!"
end
NOTE: Unlike Strukt.defstruct/1
, which inherits attributes like @derive
or @primary_key
from
the surrounding scope; this macro requires them to be defined in the body, as shown above.