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:
Last Post!
eksperimental
Modules attributes (@directions_to_the_right in this case) are just conveniences. They are replaced at compile time (known as macro in other languages). They cannot be accessed once the module has been compiled.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #hex
- #security









