22

Let say I have a struct, struct = %MyApp.MyModel{ filled_with_data: "true }.

How can I get struct name (MyApp.MyModel in my case)?

4 Answers 4

36

It's stored in a field named __struct__, so struct.__struct__ == MyApp.MyModel.

0
29

You can also get the struct name by pattern matching:

%name{} = struct
2
  • 1
    That is awesome, didn't know you could get it w/ pattern matching! Commented Aug 15, 2018 at 17:01
  • I like this because it does not rely on the :__struct__ map key, which is an implementation detail. Commented Sep 23, 2022 at 13:51
3

If you need the name of the struct as a string without the "Elixir." prefix, but keeping any of your module prefixes you can do:

name = your_map.__struct__
       |> Module.split
       |> Enum.join(".")
1
  • For the equivalent of your_map.__struct__ (where your_map is an Ecto.Schema.t struct), I didn't get the Elixir. prefix in the result just now in iex. Commented Jan 14, 2020 at 20:18
2

Structs carry __struct__

field in them. So,

struct.__struct__

should do

1
  • @Dogbert was first! Commented Sep 21, 2016 at 13:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.