theodore
Why do most functions pattern match structs on the left hand side?
Noob question. But I was just wondering, is there any advantage to pattern matching a struct on the left hand side vs right hand side?
For e.g
defmodule Test do
defstruct name: nil
def fun1(x = %Test{name: name}) do
IO.inspect(name)
end
def fun2(%Test{name: name} = x) do
IO.inspect(name)
end
end
It seems like both are equivalent, but the style of “struct on left hand side” is more common.
Here’s some other instances of what I mean
Most Liked
codeanpeace
Another reason why it’s likely more common is that it keeps things consistent.
When pattern matching outside a function head, the variable is always on the right of the = match operator since the other way around is for variable assignment
defmodule Test do
defstruct name: nil
def fun(x) do
%Test{name: name} = x
IO.inspect(name)
end
end
kip
You are right, they are functionally equivalent.
I tend to use the left hand side because when I’m scanning code, its the pattern match I want to focus on first. The binding is the second consideration - especially when there are multiple function heads matching on different constructs.
rvirding
Just to be different I prefer in Erlang to use the left hand side. To me it looks more like a pattern match which is what I am doing. ![]()
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
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance








