1
0
Fork 0
gaiety-life/content/tils/struct_pattern_matching.md
Ava Gaiety W 68305711b2 TIL
2023-09-13 09:01:27 -05:00

893 B

title date
Struct Pattern Matching Created

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.