TypeStruct (TypeStruct v1.0.0)

Copy Markdown View Source

Defines structs and their types together.

TypeStruct extends defstruct so fields can be declared as name: type, with optional defaults written as type \\ default:

defmodule Point do
  use TypeStruct

  defstruct x: integer,
            y: integer
end

It can also define nested struct modules:

defmodule Accounts do
  use TypeStruct

  defstruct User,
            id: integer,
            name: String.t() \\ "",
            eye_color: :black | :blue | :brown | :green

  defstruct Group,
            id: integer,
            name: String.t(),
            users: [User.t()] \\ []
end

Fields without defaults are required through @enforce_keys. TypeStruct defines a public t/0 type by default, and accepts type/1, typep/1, or opaque/1 to customize the generated type.

Summary

Functions

Defines a struct and a matching t/0 type in the current module.

Defines either a nested struct module or a struct with a custom type.

Defines a nested struct module with a custom type declaration.

Functions

defstruct(fields)

(macro)

Defines a struct and a matching t/0 type in the current module.

defmodule Point do
  use TypeStruct

  defstruct x: integer, y: integer
end

Fields without defaults are added to @enforce_keys.

defstruct(alias_or_type_definition, fields)

(macro)

Defines either a nested struct module or a struct with a custom type.

defmodule Geometry do
  use TypeStruct

  defstruct Point, x: integer, y: integer
end

The example above defines Geometry.Point and Geometry.Point.t/0.

If the first argument is a type declaration, the struct is defined in the current module with that type:

defstruct opaque(t), id: integer
defstruct typep(fields), id: integer

defstruct(alias, type_definition, fields)

(macro)

Defines a nested struct module with a custom type declaration.

defmodule Accounts do
  use TypeStruct

  defstruct User, opaque(t), id: integer
end

The example above defines Accounts.User and @opaque t().