What is a symbol in front of an Elixir Map?

What is the symbol in front of an Elixir map like in %Something{name: “Elixir”}?

The % is the ‘percent’-symbol, which has no other meaning in Elixir syntax besides being used to start an Elixir map.

Outside of programming, ‘X%’ it is used in mathematics to indicate ‘X of a hundred’. For instance: 25% which is another way of writing 25/100 or 1/4`. See Wikipedia for more in-depth info.

5 Likes

What’s the difference between %Something{name: “Elixir”} and %{name: “Elixir”} ?

%{} is a map, %Something{} is a struct
structs are implemented as maps, in fact they are maps with a __struct__ key

5 Likes

Think of %{} as a generic Map and %Something{} as a typed map (known as structs). Creating a type has some compile time guarantees, it ensures that the key names within the type are valid (i.e. you cannot create that type with a key which doesn’t belong). Also, it will set defaults for you if you want it to (the default default is nil).

For example:

defmodule Something do
  defstruct foo: "foo", bar: nil
end

# Will not compile because the :blah key is not part of this type
%Something{blah: true}

# Will automatically set the :foo key because it was not supplied
%Something{bar: "bar"} # equals %Something{foo: "foo", bar: "bar"}

# Default can be overridden
%Something{foo: "bar"}

In general, a plain Map should be used for unstructured data at the edges of your system (i.e. when data is entering). Structs should then be used within your own code so that the keys are known and benefit from the above benefits. When the data is on the way out of your system (to user or to a database) it can be then converted back to a plain map (or directly to JSON).

3 Likes