1
0
Fork 0
gaiety-life/content/tils/struct_pattern_matching.md
2023-09-20 17:59:59 -05:00

896 B

title date
Struct Pattern Matching 2023-09-13

Pattern Matching in Elixir feels like half of the language and may consume half of my TIL before long. But, today was the first day I realized you could specify that a pattern match could not just verify the contents of a map, but that it comes from a specific struct.

defmodule Foo do
  defstruct name: "Jade", age: 27
end # Imagine similar for Bar and Baz...

@spec my_example(%Foo{} | %Bar{}) :: %Baz()
def my_example(%Foo{} = foo), do:...

I'm finding this useful to be more specific in defining my expectations. As I continue to practice TDD I'm also practicing writing my Elixir Typespecs in the moment, rather than as an afterthought.