I’m pretty new to Elixir. One thing I don’t think I understand is the typespecs, specifically when they deal with structs. A common pattern I’ve seen is that the struct definition is frequently accompanied by a @type t
definition, something like this:
defmodule MyStruct do
defstruct x: "",
y: false,
z: 0
@type t :: %__MODULE__{
x: String.t(),
y: boolean,
z: integer
}
end
A struct is defined AND a @type t
. If I want to use this struct in function @spec
, I have seen both the struct or this type t referenced, e.g.
@spec my_func(%MyStruct{}) :: any
or
@spec my_func(MyStruct.t()) :: any
apply to a function, e.g.
def my_func(%MyStruct{} = input) do
# something...
end
So my questions are:
- Is the
@type t
special? Or is that just a convention? - Is there any difference between using
%MyStruct{}
orMyStruct.t()
in function specs? - Is there any case where you would use one and not the other?
- Is the
@type t
more “specific” because it can declare the types of various keys in the struct? (Whereas the struct itself only defines the names of the keys, not their data types)
Thanks for any clarifications. I’m sure I missed something in my studies thus far.