stevensonmt

stevensonmt

Defining types for struct fields

I would like to have a struct in a module without default values for the fields, but I would like each field to be limited to a specific type. Is there a way to define and enforce this in Elixir?

Most Liked

lud

lud

You can define a typespec for your struct but you cannot enforce it.

What you can do in your module is to use a constructor-like function:

def new(props) do
   ... validate the values
   struct(__MODULE__, props)
end

(new is not a special name)

hauleth

hauleth

I think that in this case struct!/2 (with bang) will make more sense.

lud

lud

I hesitated because if you validate the values beforehand you should not have to use it, but yes it may be safer.

@stevensonmt the difference is that struct!/2 will raise if the given props have extra properties or if keys declared with @enforce_keys are not defined.

brettbeatty

brettbeatty

You can always reduce the opts into your struct however you want. You can validate, rename, transform, do whatever.

A simple example where opts of the wrong type are simply rejected

  def new(opts \\ []) do
    Enum.reduce(opts, %__MODULE__{}, &put_opt/2)
  end

  defp put_opt(opt, acc)

  defp put_opt({:a, a}, acc) when is_integer(a) do
    %{acc | a: a}
  end

  defp put_opt({:b, b}, acc) when is_binary(b) do
    %{acc | b: b}
  end

  defp put_opt({:c, c}, acc) when is_atom(c) do
    %{acc | c: c}
  end

  defp put_opt(_opt, acc) do
    acc
  end
brettbeatty

brettbeatty

Oh sorry it’s a personal preference when I create a function with multiple clauses to have that. In my opinion it makes it clearer what the args should be, often helps with docs (for public functions), and gives me somewhere to put @doc, @spec, etc. It’s only really required when you have multiple clauses for a function that takes default arguments. https://hexdocs.pm/elixir/Kernel.html#def/2-default-arguments

Where Next?

Popular in Questions Top

albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 record...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
vac
Hi, I'm quite new in Elixir and I'm trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and ...
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list....
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers' Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
jc00ke
Expanding on this topic: https://forum.elixirforum.net/t/map-typespec-question/19217 Let’s say I have a map with required and optional k...
New

Other popular topics Top

lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
AstonJ
You’re a programmer, so you don’t need spoon feeding with the conventional drivel about “this is an integer.” No. You need to know what’s...
New
quazar
How to set Jason to encode all fields in ecto schema, I don’t care about security and implementing only is taking long list of attributes...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
beno
I will often find my self writing things similar to: case some_value do nil -> something() "" -> something() _ -> someth...
New
Nvim
Elixir appears to be a superior language to Python. I don’t see any advantage of Python over Elixir. Are there any?
New

We're in Beta

About us Mission Statement