[erlang-questions] Why use -record() ?

I Gusti Ngurah Oka Prinarjaya okaprinarjaya@REDACTED
Sun Jun 2 12:25:22 CEST 2019


Hi,

I still learn Erlang OTP from learnyousomeerlang.com especially part
https://learnyousomeerlang.com/building-applications-with-otp .

Let's see code below:

-module(ppool_serv).
-behaviour(gen_server).
....
....
-record(state, {limit=0, sup, refs, queue=queue:new()}).
....
....
init({Limit, MFA, Sup}) ->
  self() ! {start_worker_supervisor, Sup, MFA},

  %% why using -record here for state holder?
  {ok, #state{limit=Limit, refs=gb_sets:empty()}}.

>From the code above, why using record to hold state?

Other than using record we also can use tuple right? Let's see alternative
code below

-module(ppool_serv).
-behaviour(gen_server).
....
....
....
init({Limit, MFA, Sup}) ->
  self() ! {start_worker_supervisor, Sup, MFA},

  Refs = gb_sets:empty(),
  Queue = queue:new(),
  Spv = undefined,
  State = {Limit, Spv, Refs, Queue},

  {ok, State}.
...
...
...
handle_call({run, Args}, _From, {Limit, Spv, Refs, Queue}) when N > 0 ->
  {ok, Pid} = supervisor:start_child(Spv, Args),
  Ref = erlang:monitor(process, Pid),
  NewRefs = gb_sets:add(Ref, Refs),
  NewState = {Limit-1, Spv, NewRefs, Queue},
  {reply, {ok, Pid}, NewState};

We also can use the above alternative code right?

Please enlightenment


Thank you
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20190602/c7459e52/attachment.htm>


More information about the erlang-questions mailing list