Design Patterns in Rust – Singleton Pattern

The singleton pattern gives you the benefits of global access while maintaining control over how that global state is created, accessed, and modified. It’s essentially “global variables done right” for cases where you genuinely need global state.
To demo this, we’ll code an example to connect to a database.
This will involve some tinkering with docker compose, postgres as well, which will be brief but useful*
*Assuming you encounter databases but are not an expert
For more examples, check out this site : https://refactoring.guru/design-patterns/singleton/rust/example
version: '3.8'
services:
postgres:
image: postgres:15
environment:
POSTGRES_PASSWORD: demo123
POSTGRES_DB: app
POSTGRES_USER: postgres
ports:
- "5432:5432"
volumes:
- postgres_data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 10s
timeout: 5s
retries: 5
volumes:
postgres_data:
docker compose exec postgres psql -U postgres -d app -c "
CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(255) UNIQUE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
INSERT INTO users (name, email) VALUES
('Alice Johnson', 'alice@example.com'),
('Bob Smith', 'bob@example.com'),
('Charlie Brown', 'charlie@example.com')
ON CONFLICT (email) DO NOTHING;
"
❯ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
6ced1b1d666d postgres:15 "docker-entrypoint.s…" 49 minutes ago Up 49 minutes (healthy) 0.0.0.0:5432->5432/tcp, :::5432->5432/tcp youtube_videos-postgres-1