Skip to content

Instantly share code, notes, and snippets.

@masteinhauser
Last active August 29, 2015 14:05
Show Gist options
  • Save masteinhauser/708e1df865911662815a to your computer and use it in GitHub Desktop.
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
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
@CaptChrisD
Copy link

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

@CaptChrisD
Copy link

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