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).

Where Next?

Popular in Questions 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
tduccuong
Hi, is there any work on GUI with Elixir, that is similar to Electron/Javascript? My idea is to bundle Phoenix and BEAM into a single se...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
Emily
I have VueJS GUIs with the project generated using Webpack. I have Elixir modules that will need to be used by the VueJS GUIs. I forese...
New
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New
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 t...
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
komlanvi
Hi everyone, I was playing with phoenix liveView but I run into an issue. I have a form and want to validate each input text when the te...
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
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New

Other popular topics Top

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
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
New
TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
274 41989 114
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 52673 488
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New
AstonJ
We’ve put together this wiki for Phoenix LiveView - please feel free to add any info you feel is worth including. What is Phoenix LiveV...
New
vegabook
I’m brand new to Phoenix and I have stripped one of the demo applications to the bone. I just want to get an svg up on the screen. Here i...
New

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement