Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get struct name in elixir?

Tags:

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

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

like image 897
asiniy Avatar asked Sep 21 '16 13:09

asiniy


People also ask

How is struct elixir defined?

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.

What is __ module __ In elixir?

__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.

How do you convert struct to Elixir map?

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.


1 Answers

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

like image 130
Dogbert Avatar answered Sep 17 '22 17:09

Dogbert