I recently came across a code snippet such as:
def loop(ring_pid \\ self, nil, true) do
#some code
end
What do the double backslashes mean? I googled around and found http://elixir-lang.org/getting-started/sigils.html, but that applies to regular expressions not function params.
It specifies a default value.
Function arguments defined using \\
after the argument name are providing an optional default. So if loop/2 is called, the first argument will be the pid returned from self()
. If loop/3 is called, then you would specify a pid.
Let's take another (trivial) example:
math.ex
defmodule Math do
def add(a \\ 2, b) do
a + b
end
end
iex (1)> c("math.ex")
iex (2)> Math.add(1, 8) # add/2, because you are matching 1 to `a`.
9
iex (3)> Math.add(8) # add/1, because `a` is by default matched to 2.
10
\\
is used to define default params, source
You can observe that behavior by trying it in the iex
console, for instance:
defmodule Foo do
def bar(x \\ 1, y) do
x * y
end
end
Foo.bar(2,3) # => 6
Foo.bar(3) # => 3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With