Quick start
Use this guide in an existing Gleam application. You will save two entries, stop the application, and read the entries in a second run.
1. Add shelf and create a data directory
Section titled “1. Add shelf and create a data directory”From your project directory, run:
gleam add shelfmkdir -p /tmp/shelf-quick-startThis example uses a temporary directory. For application data you need to keep, choose a directory that survives system cleanup.
2. Write and save the entries
Section titled “2. Write and save the entries”Replace your application's main module with:
import gleam/dynamic/decodeimport gleam/ioimport shelf/set
pub fn main() -> Nil { let assert Ok(table) = set.open( name: "users", path: "users.dets", base_directory: "/tmp/shelf-quick-start", key: decode.string, value: decode.int, )
let assert Ok(Nil) = set.insert(into: table, key: "alice", value: 42) let assert Ok(Nil) = set.insert(into: table, key: "bob", value: 99) let assert Ok(42) = set.lookup(from: table, key: "alice")
let assert Ok(Nil) = set.save(table) let assert Ok(Nil) = set.close(table) io.println("Saved users to DETS.")}Run gleam run. The application prints Saved users to DETS. and exits.
Writes use ETS in the default WriteBack mode. save() snapshots them to
DETS; successful close() also saves before releasing the table.
3. Read the saved entries in a new run
Section titled “3. Read the saved entries in a new run”Replace the main module with this version, which does not insert any data:
import gleam/dynamic/decodeimport gleam/ioimport shelf/set
pub fn main() -> Nil { let assert Ok(table) = set.open( name: "users", path: "users.dets", base_directory: "/tmp/shelf-quick-start", key: decode.string, value: decode.int, )
let assert Ok(42) = set.lookup(from: table, key: "alice") let assert Ok(99) = set.lookup(from: table, key: "bob") let assert Ok(Nil) = set.close(table) io.println("Saved users loaded from DETS.")}Run gleam run again. The message Saved users loaded from DETS. confirms
that the second application loaded the saved entries. Your decoders checked
their keys and values before they reached ETS.
The let assert statements make this small example stop on an error.
In application code, handle the returned Result so you can report or
recover from storage errors.
Choose your next step
Section titled “Choose your next step”Use set tables for one value per key, or bag tables for distinct values under one key. To decide when changes reach DETS and what survives a crash, read write modes. For save, reload, sync, and close behavior, see persistence operations.