elixir struct

defmodule UserModule do
  
  # UserModule struct definition
  # Put this inside a module definition
  defstruct [:first_name, :last_name, :age]


  # functions to access the struct data,
  # horever if the struct and functions life in the same module, 
  # you can replace the module name with __MODULE__  attributte. 
  
  # Ej %UserModule{} is the same that %__MODULE__{}

  def first_name(%__MODULE__{first_name: name}),
    do: name

  def last_name(%__MODULE__{last_name: name}),
    do: name

  def age(%__MODULE__{age: age}),
    do: age

end

# For usage this, you can do (in iex for example):

> user = %UserModule{first_name: "martin", last_name: "alganaraz", age: 40}
> UserModule.first_name user
"martin"

3.83
6

                                    # struct example
%__MODULE__{
	name: "apple",
	location: {40,0,1},
}

3.83 (6 Votes)
0
Are there any code examples left?
New code examples in category Elixir
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source