gen_server handle_info/2 clarification

While reading through Erlang and OTP in action, I ran across some weird syntax regarding records that I’m having trouble wrapping my head around. I’m hoping someone can clarify what’s going on in the handle_info for timeouts here:

handle_info({tcp, Socket, RawData}, State) ->
    do_rpc(Socket, RawData), 
    RequestCount = State#state.request_count, 
    {noreply, State#state{request_count = RequestCount + 1}}; 

handle_info(timeout, #state{lsock = LSock} = State) -> 
    {ok, _Sock} = gen_tcp:accept(LSock), 
    {noreply, State}.

Specifically, I’m not quite sure what’s going on here:

#state{lsok = LSock} = State

It appears to be some sort of reverse assignment? Are you effectively saying the second argument will be a #state record, to assign the lsock value to LSock variable and assign the whole record to State? I’m just inferring that from how the variables are used in the next two lines, but that syntax seems weird.


I did some more testing of pattern matching and assignment in the shell, and it isn’t working as I expected:

2> 1 = A.
* 1: variable 'A' is unbound
3> A = 1.
4> {1,2}.
5> {1,2} = B.
* 1: variable 'B' is unbound

Then I ran this test function to see if maybe it was just in matching function arguments:

test_assignment(A = {X,Y},{W,X} = B) ->
    io:format("Variable A is ~p~n",[A]),
    io:format("Variable B is ~p~n",[B]).

24> c(test).                              
test.erl:21: Warning: variable 'W' is unused
test.erl:21: Warning: variable 'Y' is unused
25> test:test_assignment({1,2},{3,4}).
** exception error: no function clause matching test:test_assignment({1,2},{3,4}) (test.erl, line 21)

Source: syntax

Leave a Reply