You cannot view this unit as you're not logged in yet. Go to Account to login.

3 Comments

  1. McKinnin Lloyd on January 27, 2020 at 10:04 pm

    I have a question. Why in the function get_name it will throw an error if you do %User{name: name} and not %{name: name}, but in the create_greeting function it is opposite. In that function it wants you to do %User{name: name}?

    • brainlid on January 28, 2020 at 6:20 am

      That’s a good question! In the get_name example, we want the pattern to be less specific. By not specifying the struct type, we match on any map data type (including structs) but only if they have a key called :name. For get_name, it would also be valid to write this:

      def get_name(%Customer{name: name}), do: {:ok, name}
      def get_name(%User{name: name}), do: {:ok, name}
      def get_name(_other), do: {:error, "Doesn't have a name"}

      This is more specific. We give an explicit pattern match on a customer and user struct. However, the results of the functions are identical. It doesn’t actually matter that it’s a Customer or a User struct type. It is better to match more generally to only the data that we actually care about for getting the :name from the data.

      Then in the create_greeting function we want to be more specific with our match because we want a different result based on the data type.

      Another way to describe the behavior in get_name is like this: “if the data has a key called :name then return the value”. It doesn’t care about what kind of struct. Then create_greeting is saying “if it is a customer then greet this way. If it is a user then greet this other way.” The best way to tell them apart is by their struct types.

      Did I answer your question?

  2. romenigld on December 14, 2020 at 7:42 am

    I loved this example.
    It’s like when you will refactor the code.
    You match on any map data type (including structs) and has less lines of code to write and understand.
    Thank’s!

Leave a Comment

You must be logged in to post a comment.