tadiou

tadiou

Why can you remove fields from defstructs's maps if you can't add them?

I was just going through some stuff with some jr. devs about how structs work, and we were fooling around with what can be done with them as an exercise, and then… well. We struct (lol) something I wasn’t able to explain away. Assume:

defmodule Cat do
  defstruct type: nil, weight: nil
end 

Obviously, %Cat{variance: "tabby"} fails with keyerror, because variance doesn’t exist on the struct, and if you did go %Cat{}, you’d receive %Cat{type: nil, weight: nil}… And further if you try to go with

%{%Cat{} | variance: "tabby"}

again, it checks that you can’t add something that was defined. You get some semblence of safety when it comes to the values of what you can expect on a struct. On defined Cat struct, it’d contain the values of type and `weight.

But… Map.delete(%Cat{type: "Maine Coon"}, :weight) gives you the appearance of a valid(?) struct still.

%{__struct__: Cat, type: "Maine Coon"}

At no point does it give the indication that it’s out of step with the struct and I haven’t been able to find out how to validate that. I’d expect on create time we’d handle the checks, but when modifying post-create, there’s no integrity checks here. I thought that maybe Kernel.struct/2 might be a use to validate here, but it comes out clean.

Obviously this is a much smaller issue when you’re using Ecto and changesets, but it was something that really quirked me a bit! TIA for the explaination.

Most Liked

axelson

axelson

Scenic Core Team

The fact that you can see the :__struct__ key in the inspect output is meant to warn you that you no longer have a valid %Cat{} struct.

You get a similar error if you add a non-existant key to a struct directly with Map.put:

iex> Map.put(cat, :some_bad_key, "val")
%{__struct__: Cat, some_bad_key: "val"}
al2o3cr

al2o3cr

It’s present, that’s how inspect knows to format it as %Cat{...} instead of %{...}.

You can even write code that matches on __struct__:

def thing_that_captures_struct(%struct_var{} = input) do
  # if you pass in a %Cat{}, "input" will be bound to the atom Cat
end

Nitpick: since this has a complex expression on the left-hand side, “initialize” is not quite the right verb - as the error message says, this is a failure to match. This would be fine:

%{__struct__: Cat} = %Cat{type: "Maine Coon"}

since the match requires all the keys in the map on the left to be present in the map on the right.

Nicd

Nicd

Structs are only maps underneath, with some compiler guarantees. In this case, the compiler cannot infer that the deletion should not happen, so it cannot warn about it. In theory the Map.delete function could check if the given map has a :__struct__ key at runtime, but currently it doesn’t do that (and I don’t think it will be changed).

Sebb

Sebb

Just don’t break the structs, Elixir is a dynamic language and requires some countenance.

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

And in my experience they’re pretty hard to make in real world code by accident. I’ve been coding Elixir full time since structs were added to the language and I can’t think of any time this has been an issue for me.

Where Next?

Popular in Questions Top

srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call th...
New
dotdotdotPaul
Okay, I'm having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I'm sure I'...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod -- where is this set? Thanks.
New
dokuzbir
Hello, I am trying to convert my lists to string without losing brackets.For start i have 3 map. They look like these buyer = %{ id: ...
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
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
mathew4509
I have a list say x = ["23gh", "56kh", "97mh"] I would like to pass each element to Val in each iteration. Say, in iteration 1 -------...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New

Other popular topics Top

senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
dotdotdotPaul
Okay, I'm having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I'm sure I'...
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
yawaramin
In the Dialyzer docs ( http://erlang.org/doc/man/dialyzer.html#requesting-or-suppressing-warnings-in-source-files ), there is a way to tu...
New
axelson
This post is a wiki (feel free to hit the edit button near the bottom right of this post to add your own changes!) This post collects co...
239 45766 226
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
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
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID<0.412.0> terminating ** (Postgrex.Error) FATAL...
New

We're in Beta

About us Mission Statement