Iggy
Iggy

Reputation: 5251

What are some usages for make_ref() function in elixir?

I saw a code snippet making use of make_ref() and not sure about the usability of this function.

The hexdocs says:

Returns an almost unique reference.

The returned reference will re-occur after approximately 2^82 calls; therefore it is unique enough for practical purposes.

Inlined by the compiler.

But it does not really say when or why I should use it. Why would I use it and when should I use it? It seems to me that all it does is generate random numbers. Why can't I just use some sort of random number generator?

This is what it does on terminal:

iex(1)> make_ref()
#Reference<0.3569050097.3772514305.191818>
iex(2)> make_ref()
#Reference<0.3569050097.3772514305.191837>
iex(3)> make_ref()
#Reference<0.3569050097.3772514307.194286>

Upvotes: 8

Views: 2952

Answers (2)

Alex Wolf
Alex Wolf

Reputation: 20158

I've seen it used as a "uniqueness" flag when sending messages.

See this example from db_connection:

def run_child(mod, fun, state, opts) do
  ref = make_ref()
  arg = [mod, fun, ref, self(), state, opts]
  {:ok, pid} = Task.Supervisor.start_child(__MODULE__, __MODULE__, :init, arg)
  mon = Process.monitor(pid)
  send(pid, {:go, ref, mon})
  {pid, mon}
end

def init(mod, fun, ref, conn, state, opts) do
  # ...
  receive do
    {:go, ^ref, mon} ->
      # ...
  end
end

Here make_ref/0 is used to send a message which can only be received by the process knowing the reference. It's a relatively easy way to restrict process communication to a particular "scope".

Apart from that mudasobwa's answer is certainly correct.

Upvotes: 4

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121010

:erlang.make_ref/0 returns a reference that is unique among connected nodes.

It is mostly the legacy of before-UUID era. That said, just the random generator won’t be sufficient enough: it should generate something unique across different machines.

UUID could be a good alternative for references unless you are concerned about the memory load: references are way more efficient.

Also, calling make_ref is [arguably] handier than dealing with kinda UUID generator.

Upvotes: 12

Related Questions