Pointers in Elixir
Elixir supports the concept of processes and message passing, which are somewhat analogous to pointers in terms of sharing and modifying data. We’ll demonstrate this using two functions: zero_val
and zero_pid
.
In this Elixir example, we’ve created two functions to demonstrate the difference between passing values and using processes (which are Elixir’s lightweight threads):
zero_val
takes a value as an argument. It assigns 0 to a new variable, but this doesn’t affect the original value.zero_pid
takes a process ID (PID) as an argument. It sends a message to the process, which can change its internal state.
In the run
function:
We create an initial value
i = 1
.We call
zero_val(i)
, which doesn’t change the value ofi
.We spawn a new process that runs the
loop
function with the initial value ofi
. This process can receive messages to change its state or return its current value.We call
zero_pid(pid)
, which sends a message to the process to change its internal value to 0.We then send a message to get the current value from the process and print it.
Finally, we print the PID of the spawned process.
The loop
function demonstrates how a process can maintain state and respond to messages. It can receive a :zero
message to set its value to 0, or a :get
message to send its current value back to a requester.
When you run this program, you should see output similar to this:
This demonstrates that zero_val
doesn’t change the original value, while zero_pid
effectively changes the state of the process. The PID is a unique identifier for the spawned process.
In Elixir, processes and message passing are used for managing shared state and concurrency, serving a similar purpose to pointers in languages like C or Go, but with different semantics and safety guarantees.