Get field names of a struct

Hello,

Is there a way to get the list of fields with only the struct module?

iex> something(Date)
[:calendar, :year, :day, :month]

I tried this, but it doesn’t work if @enforce_keys are defined:

iex(4)> Map.keys(%Date{})
** (ArgumentError) the following keys must also be given when building struct Date: [:year, :month, :day]
    (elixir) expanding struct: Date.__struct__/1
    iex:4: (file)

At first glance it does not seem that any function is created for this either:

1 Like

This seems to work:

iex(2)> Date.__struct__() |> Map.keys()
[:__struct__, :calendar, :day, :month, :year]
5 Likes

This seems to work for any struct:

struct(Foo, %{}) |> Map.from_struct() |> Map.keys()

2 Likes

I’d like to know if there is any way to introspect struct fields obtaining the order they were defined in defstruct? For background I’m doing some macros with structs to implement various protocols, and would like to default the ordering but map.keys is of course unordered.