6
votes

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?

2

2 Answers

9
votes

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

7
votes

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)