Convert a Keyword List to a Struct
You can use Kernel.struct/2
to convert a keyword list (or Enumerable) into a struct.
I found this useful when working with a new social media integration. I read some key-values out of the config environment and needed to convert these into a named struct.
> creds = Application.get_env(:tilex, __MODULE__)
[username: "foo", password: "bar"]
> struct(BlueskyEx.Client.Credentials, creds)
%BlueskyEx.Client.Credentials{
username: "foo",
password: "bar"
}
When you pass keys that are not part of the struct, they are discarded for you. If you want to raise an error, you can use the related struct!/2
function
https://devdocs.io/elixir~1.17/kernel#struct/2
Tweet