What's the difference in how you can access Map fields?

Hello,

I have some trouble accessing elixir maps, I didn’t figure out the way to because there is 3 ways :

body = %{
        test: value
      }

Do we access the "test field by :

  • body[“test”
    or
  • body[:test]
    or
    body.test

what is the difference between the 3 ways ?

thanks

1 Like

Hey @xgeek116

body["test"]

This one won’t work, because it looks for a key that is "test". "test" is a string, but your key is :test which is an atom.

body[:test]

This will work and return the value. If you put in a key that does not exist in the map like body[:hello] it will return nil.

body.test

This will also work and return the value. If you use a key that does not exist like body.hello it will raise an exception.

10 Likes