cblavier
Struct pattern matching
Hey there ![]()
I have the 2 following structs.
defmodule Variation do
@enforce_keys [:id, :attributes]
defstruct [:id, :description, :attributes, :slots, :block]
end
defmodule VariationGroup do
@enforce_keys [:id, :variations]
defstruct [:id, :description, :variations]
end
I would like to pattern match both structs at once, based on the fact they share similar attributes: :id and :description.
Is this achievable through behaviors?
Marked As Solved
fuelen
Another options:
def test(%module{}) when module in [Variation, VariationGroup], do: ...
def test(term) when is_struct(term, Variation) or is_struct(term, VariationGroup), do: ...
Also Liked
JohnnyCurran
Just treat them as maps:
def my_func(%{id: id, attributes: attributes}) do
# work
end
And if you need to access the underlying module:
def my_func(%{id: id, attributes: attributes} = entity) do
entity.__struct__
end
michallepicki
If you want to share the implementation of a function from a protocol, you can move it to a different module and delegate there from all separate protocol implementations. Or you can create a separate protocol for the shared parts and pass a list of struct modules (or primitive types if applicable) to defimpl.
Last Post!
michallepicki
If you want to share the implementation of a function from a protocol, you can move it to a different module and delegate there from all separate protocol implementations. Or you can create a separate protocol for the shared parts and pass a list of struct modules (or primitive types if applicable) to defimpl.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #hex
- #security









