Let say I have a struct, struct = %MyApp.MyModel{ filled_with_data: "true }
.
How can I get struct name (MyApp.MyModel
in my case)?
To define a struct we use the defstruct construct with the fields we want. So let's include “country_code”, “area_code”, and “number”. Now that we've defined our struct, let's go to the command line. And we'll start an IEx session with our project.
__MODULE__ is a compilation environment macros which is the current module name as an atom. Now you know alias __MODULE__ just defines an alias for our Elixir module. This is very useful when used with defstruct which we will talk about next. In the following example, we pass API.
defmodule BestStructEver do defstruct [:a] end # Struct to simple map: iex> Map. from_struct(%BestStructEver{a: "foobar"}) # => %{a: "foobar"} # Map to a struct: iex> struct(BestStructEver, %{a: "foobar"}) # => %BestStructEver{a: "foobar"} # Note: The struct function is from Kernel, so `Kernel.
It's stored in a field named __struct__
, so struct.__struct__ == MyApp.MyModel
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With