singhvisamit
Structs for a toy robot
@directions_to_the_right %{north: :east, east: :south, south: :west, west: :north}
def right(%ToyRobot.Position{facing: facing} = robot) do
%ToyRobot.Position{robot | facing: @directions_to_the_right[facing]}
end
This is the code. Normally in elixir we define structs like-
%Structname{key:value}
But here what is the significance of this @ and % after Struct’s name
First Post!
Benjamin-Philip
Here’s the syntax highlighted code:
@directions_to_the_right %{north: :east, east: :south, south: :west, west: :north}
def right(%ToyRobot.Position{facing: facing} = robot) do
%ToyRobot.Position{robot | facing: @directions_to_the_right[facing]}
end
That’s how you might initialise a struct. In order to define a struct, you use defstuct
The @ is used to assign a module attribute, so @directions_to_the_right is a module attribute.
This
%{north: :east, east: :south, south: :west, west: :north}
however is a map and not a struct.
In
%ToyRobot.Position{robot | facing: @directions_to_the_right[facing]}
We are updating the value of the facing key, but accessing the value of the direction to the right from @directions_to_the_right.
For more info and structs and maps see:
https://elixir-lang.org/getting-started/keywords-and-maps.html







