Struct v1.0.0 Struct behaviour View Source
Struct internally divided into three components:
Struct— defining structs;Struct.Cast— making struct instances;Struct.Type— type-coercion and custom type behaviour.
Struct definition
defmodule StructureName do
use Struct, struct_opts
structure do
include AnotherStruct
field name, type, options
end
end
struct_opts is options passed to make/2 and make!/2, described in Struct.Cast.make/3.
When you type use Struct — library bootstrapped few functions with Struct behaviour:
make/2— just an alias toStruct.Cast.make/3;make!/2— alias tomake/2but throwsStruct.MakeErrorexception if provided params are invalid;cast/2— alias tomake/2too, for followStruct.Typebehaviour and use defined struct as type.
Link to this section Summary
Functions
Defines field on the structure with given name, type and options
Includes provided structure and checks definition for validity at compile-time
Defines a structure
Callbacks
Alias to make/2, used to follow Struct.Type.cast/1 callback
Alias to Struct.Cast.make/3
Alias to make/2, but raises an Struct.MakeError exception if params have errors
Link to this section Types
Link to this section Functions
field(atom(), Struct.Type.t(), Keyword.t()) :: :ok
Defines field on the structure with given name, type and options.
Checks definition validity at compile time by name, type and options.
For custom types checks for module existence and Struct.Type.cast/1 callback.
If field definition is invalid for some reason — it throws an Struct.DefinitionError
exception with detailed reason.
Options
:default— sets default value for that field:The default value is calculated at compilation time, so don’t use expressions like DateTime.utc_now or Ecto.UUID.generate as they would then be the same for all structs;
Value from params is compared with default value before and after type cast;
If you pass
field :a, type, default: nilandmake(%{a: nil})— type coercion will not be used,nilcompares with default value and just appends that value to struct;If field doesn’t exist in params, it will use default value.
By default this option is unset. Notice that you can’t use functions as a default value.
Includes provided structure and checks definition for validity at compile-time.
If included structure is invalid for some reason — this macro throws an
Struct.DefinitionError exception with detailed reason.
Defines a structure.
Link to this section Callbacks
Alias to make/2, used to follow Struct.Type.cast/1 callback.
To use this struct as custom type.
Alias to Struct.Cast.make/3.
Alias to make/2, but raises an Struct.MakeError exception if params have errors.