Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access struct inside module where struct defined [Elixir]

Tags:

elixir

I'm in the very beginning of learning Elixir, but have a programming background with several OOP languages, mostly Ruby. I found example how I can define struct inside module:

defmodule Example.User do
  defstruct name: "Sean", roles: []
end

Also, I found I can set this value when I create structs: steve = %Example.User{name: "Steve", roles: [:admin, :owner]} and can access it outside module just by calling steve.name

The question is, how can I access struct data INSIDE module, so let's say I want to access name field from call_my_name function:

defmodule Example.User do
  defstruct name: ""
  def call_my_name do
     IO.write(???)
  end 
end
martin = %Example.User{name: "Martin"}

In terms of OOP, I just trying to write a getter.

How can I do it? What is a good/default way to do it? If I can't, why?

like image 707
Yaroslav V. Avatar asked Oct 04 '16 13:10

Yaroslav V.


2 Answers

Just to pile on here, you don't need to use the full namespace within your own module, so long as you don't have another User module to reference. Try this:

defmodule Example.User do
  alias __MODULE__ # <- this is the magic

  defstruct [:name]

  def my_fun(%User{} = user)
    IO.inspect(user)
  end
end

Thanks to https://dockyard.com/blog/2017/08/15/elixir-tips for the tip

like image 181
Michael Lapping Avatar answered Nov 14 '22 19:11

Michael Lapping


Although the syntax might look similar to Ruby at first, Elixir is not an OOP language. You don't have "methods" in Elixir. Instead, you need to explicitly call the function and pass in the struct:

defmodule Example.User do
  defstruct name: ""

  def call_my_name(%Example.User{name: name}) do
     IO.write(name)
  end 
end

martin = %Example.User{name: "Martin"}
Example.User.call_my_name(martin)
like image 7
Dogbert Avatar answered Nov 14 '22 19:11

Dogbert