stevensonmt

stevensonmt

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?

Showing Posts 1 to 10

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.

stevensonmt

stevensonmt OP

Thank you! If using struct!/2 it may raise an exception at runtime and crash, but if using the suggested new/1 constructor you can handle the exceptions gracefully, is that right?

lud

lud

No because as I’ve said, new is not special, it is just a function that you have to define (you could call it create or anything else), and in that function (see my snippet) you call either struct/2 or struct!/2. So it is up to you if you allow to raise.

stevensonmt

stevensonmt OP

Oh, I see, struct vs struct! in the constructor function. Thanks!

al2o3cr

al2o3cr

AFAIK using either struct or struct! doesn’t let Dialyzer “see” what’s happening, and that’s what’s doing the type-enforcement when you use something like typed_struct. The only difference between the two is that struct silently ignores keys it doesn’t understand, while struct! raises.

Writing a literal will complain, though: %SomeStruct{key: "value_of_wrong_type"}.

You could accomplish a similar result by carefully type-specing your new function as well.

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
stevensonmt

stevensonmt OP

That’s a great tip. Can I ask what the first defp put_opt(opt, acc) without further definition is for?

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. Kernel — Elixir v1.20.2

Where Next? Top

Trending in Questions Top

stjefim
Hello! Suppose you are building workflow (order / task / payment) processing system with the following requirements: Each workflow con...
New
Blokh
Hey guys, I’ve got a huge CSV ( around 10 GB ) that needs to be processed hourly Do you guys have any suggestions what is the best prac...
New
kszambelanczyk
Hello! Could someone please give me a help/sample code, how to delete a file from s3 using waffle/waffle_ecto from Phoenix app. I creat...
New
Onor.io
I have what I’ve heard referred to as a “lookup table” in my database. This is a way of assigning codes to common values. One common lo...
New
jaybe78
Hello, I’m developing a online persistent chat system (what’s app) like using elixir/dynamodb/aws for a mobile app(flutter). The diffic...
New
Trolleger
What approach to take when sending live updates to “random” users Hi! I have a question, I have a little chat app, and when I create a DM...
New
widianto
I think I’ve found a small improvement I could contribute to <%= web_namespace %>.CoreComponents (installer/templates/phx_web/compo...
New

Other Trending Topics Top

garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge & Solve. They are GUI (Emerge) and State management (S...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
wintermeyer
There are three potential reasons for members of this forum to have a look at https://vutuv.de You are tired or annoyed of LinkedIn. Yo...
New
webofbits
Aludel - LLM Evaluation Workbench Aludel is an embeddable Phoenix LiveView dashboard for evaluating and comparing LLM prompts across mult...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews