Dynamically get list of struct keys

Is it possible to get a list of all keys in a struct? for instance a variable x holds a struct and I want to get a list of all its keys. The inspect does not seem to do this. Is the only way to do this to convert the struct to a map? Thank you for your assistance!

Hello, structs are special forms of maps, so Map.keys/1 does list a struct’s keys.
I.e.

iex(1)> d = Date.utc_today()
~D[2021-01-12]
iex(2)> Map.keys(d)       
[:__struct__, :calendar, :day, :month, :year]

hth

2 Likes

Ah, this makes sense. Thank you!

You can pass the option structs: false to inspect to see what’s inside the struct

iex> IO.inspect 1..2, structs: false
%{__struct__: Range, first: 1, last: 2}
1..2
3 Likes