Skip to content

Instantly share code, notes, and snippets.

@Mazuh
Created February 18, 2026 20:24
Show Gist options
  • Select an option

  • Save Mazuh/bf41ef24bb26ae1a2de0296be5ca215b to your computer and use it in GitHub Desktop.

Select an option

Save Mazuh/bf41ef24bb26ae1a2de0296be5ca215b to your computer and use it in GitHub Desktop.
Elixir, Fake OOP with Agents
defmodule Person do
use Agent
def new(name) do
{:ok, pid} = Agent.start_link(fn -> %{name: name} end)
%{
greet: fn -> greet(pid) end,
get_name: fn -> get_name(pid) end,
set_name: fn new_name -> set_name(pid, new_name) end
}
end
defp get_name(pid), do:
Agent.get(pid, & &1.name)
defp set_name(pid, new_name), do:
Agent.update(pid, &%{&1 | name: new_name})
defp greet(pid), do:
"hello i am #{get_name(pid)}"
end
person = Person.new("marcell")
person.greet.() |> IO.puts()
# Output: "hello i am marcell"
person.set_name.("amanda")
person.greet.() |> IO.puts()
# Output: "hello i am amanda"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment