otuv

otuv

%Struct{} vs %{__struct__: Struct}

Hi,

Lets say I have a struct, lets say named Struct with the singular field x (default 0).

When I create it I get &Struct{x: 0}
Since they are maps I then use Map.put to add something else like y: 5 I get %{struct: S, x: 0, y: 5} and it is no longer an Stuct

Is there some way to purge any non struct fields and restore it to an Struct?

(Here the whole idea is obviously stupid)

Marked As Solved

gregvaughn

gregvaughn

Here’s one approach. I chose the URI struct because it’s small and in the std lib.

iex(39)> u = URI.parse "http://elixirforum.com"
%URI{
  authority: "elixirforum.com",
  fragment: nil,
  host: "elixirforum.com",
  path: nil,
  port: 80,
  query: nil,
  scheme: "http",
  userinfo: nil
}
iex(40)> m = Map.put(u, :y, 5)
%{
  __struct__: URI,
  authority: "elixirforum.com",
  fragment: nil,
  host: "elixirforum.com",
  path: nil,
  port: 80,
  query: nil,
  scheme: "http",
  userinfo: nil,
  y: 5
}
iex(41)> s = struct(m.__struct__, Map.from_struct(m))
%URI{
  authority: "elixirforum.com",
  fragment: nil,
  host: "elixirforum.com",
  path: nil,
  port: 80,
  query: nil,
  scheme: "http",
  userinfo: nil
}

struct/2 ignores keys that are not specified in the struct itself

Also Liked

ityonemo

ityonemo

you can also use map cons, if you would like for your code to crash when you try to assign a nonexistent field, lets you catch errors in tests (how good is your test coverage? lol)

defmodule S do
  defstruct [x: 0]
  def do_something(val = %S{}) do
     %{val | y: "oops"}
  end
end

will crash on do_something. Whenever it’s a struct, I prefer using map cons for that bailout behaviour.

brettbeatty

brettbeatty

I prefer the previous answer, but another option would get a list of keys expected in the struct and take them from the map.

Building on the other example:

iex> Map.take(m, Map.keys(%URI{}))
%URI{
  authority: "elixirforum.com",
  fragment: nil,
  host: "elixirforum.com",
  path: nil,
  port: 80,
  query: nil,
  scheme: "http",
  userinfo: nil
}

Two downsides to this approach compared to the previous:

  1. This solution won’t replace any missing keys.
  2. This approach doesn’t let you create the struct dynamically (not without wrapping it in struct/0 at least, which at that point you might as well do the other).

Where Next?

Popular in Questions Top

bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
pgiesin
This should be a simple problem but I just can’t seem to figure it out. I have a standalone Elixir app that won’t find the database. Dep...
New
sacepums
Hey guys. I'm new to elixir and im really stocked about it. But I ran into a bit of problem - I need to convert a date sting, for examp...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
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
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
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
hpopp
To simplify some tasks at work, I wrote and published this package yesterday. It’s a simple macro that enables Access behaviour on struct...
New

Other popular topics Top

sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
Tee
can someone please explain to me how Enum.reduce works with maps
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
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
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
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
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
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
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

We're in Beta

About us Mission Statement