View Source TypeCheck.Defstruct (TypeCheck v0.13.7)

Implements the defstruct! macro.

To use this macro:

  • Ensure you use TypeCheck in your module
  • Also use TypeCheck.Defstruct

And now call defstruct!/1 when you want to define a struct.

Summary

Functions

Defines a struct and a TypeCheck type at the same time.

Functions

Link to this macro

defstruct!(fields_with_types)

View Source (macro)

Defines a struct and a TypeCheck type at the same time.

Example:

defmodule User do
  use TypeCheck
  use TypeCheck.Defstruct

  defstruct!(
    name: "Guest" :: String.t(),
    age: _ :: non_neg_integer()
  )
end

This is syntactic sugar for:

defmodule User do
  use TypeCheck
  use TypeCheck.Defstruct

  @type! t() :: %User{
    name: String.t(),
    age: non_neg_integer()
  }
  @enforce_keys [:age]
  defstruct [:age, name: "Guest"]
end

Optional and required keys

A key is considered optional if it uses the syntax

name: default_value :: type

A key is considered required if it uses one of the following syntaxes:

:name :: type

name: _ :: type

In this case, it will be added to the @enforce_keys list. (c.f. Kernel.defstruct).