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

16 lines
No EOL
896 B
Markdown

---
title: Struct Pattern Matching
date: 2023-09-13
---
[Pattern Matching in Elixir](https://elixir-lang.org/getting-started/pattern-matching.html) 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.
```elixir
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](https://www.agilealliance.org/glossary/tdd) I'm also practicing writing my [Elixir Typespecs](https://elixir-lang.org/getting-started/typespecs-and-behaviours.html) in the moment, rather than as an afterthought.