16 lines
No EOL
893 B
Markdown
16 lines
No EOL
893 B
Markdown
---
|
|
title: Struct Pattern Matching
|
|
date: Created
|
|
---
|
|
[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. |