Last active
August 29, 2015 14:05
-
-
Save masteinhauser/708e1df865911662815a to your computer and use it in GitHub Desktop.
Elixir: Match two fields of a struct against each other in a function definition
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def foo(%State{attempted_address} = address, bar)) when address not nil do | |
# a thing, do it here | |
end | |
def foo(%State{address} = address, bar)) when address not nil do | |
# a thing, do it here | |
end |
Thanks for the help, but I might not be asking this clearly.
Here is more details
I have a struct that stores the state for my GenServer
defmodule State
@derive [Access]
defstruct attempted_address: nil, other_stuff: nil
end
Then during init the attempted_address gets set base on some conditions.
state = %State{attempted_address: 37}
Then eventually a message comes in that requires a function call but I only want the function to match based on the address it is sent too. This is the address stored in the state (37 in this case)
So I have a call
foo(37, :hello)
then I have functions:
def foo(state.attempted_address, message) do
#message for us so process
end
def foo(address, message) do
#Forward message to someone else since it is not for us
end
but of course I cannot do state.attempted_address since this is not allowed.
Thank you again for help with this. I have tried everything I can think of
I don't think
%State{address} = address
is valid... I get a compile error
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks but I don't think this quite what I am looking for... I really want the equivalent of:
def foo(state.bar, b) do
#stuff
end