Skip to content

ETS

ETS stores mutable data in a table owned by a process. This example uses an unnamed private set for cached scores. Its handle fixes the key and value types, and the owning process is responsible for the table’s lifetime.

A map update produces a new map. An ETS insert changes a table in place; subsequent lookups through its handle observe the change. A :set stores one value per key, so inserting a score for the same name replaces its old score.

mod ets
@moduledoc """
ETS stores mutable data in a table owned by a process. This example uses an
unnamed private set for cached scores. Its handle fixes the key and value
types, and the owning process is responsible for the table's lifetime.
"""
alias gale_std.ets as tables
pub type Scores = tables.Ets<:scores, String, Integer>
pub fn new() -> Result<Scores, tables.EtsError> {
tables.new(:scores, [:set, :private])
}
pub fn put(scores: Scores, name: String, score: Integer) -> Result<Boolean, tables.EtsError> {
tables.insert(scores, name, score)
}
pub fn find(scores: Scores, name: String) -> Result<List<Integer>, tables.EtsError> {
tables.lookup_all(scores, name)
}
pub fn remove(scores: Scores, name: String) -> Result<Boolean, tables.EtsError> {
tables.delete(scores, name)
}

find returns Ok([]) for a missing name and Ok([score]) for a stored score. A native access failure is an Error, distinct from a missing entry. The library returns lists because other ETS table kinds can store multiple objects under one key.

These tables are unnamed: two calls to new create separate tables even though both use :scores. The process that creates a table owns it. A private table allows only that process to read and write; it is deleted when its owner exits. The tests create tables inside their own test processes, so they are cleaned up when those processes finish.

Use :protected for other processes to read while only the owner writes, or :public to allow other processes to read and write. A long-lived cache needs a long-lived owner, often a GenServer. Individual ETS operations do not make a sequence of lookups and writes atomic.

Ets<:scores, String, Integer> records the table identity type, key type, and value type. Typed calls enforce those types. Native Elixir writers must obey the same pair layout and types; the handle cannot validate arbitrary foreign writes or guarantee that a table still exists. tables.named is a trusted attachment to an existing table, not a runtime validation step.