package deps
import "sync"
type Lazy[T any] struct {
once sync.Once
v T
err error
init func() (T, error)
}
func NewLazy[T any](init func() (T, error)) *Lazy[T] {
return &Lazy[T]{init: init}
}
func (l *Lazy[T]) Get() (T, error) {
l.once.Do(func() {
l.v, l.err = l.init()
})
return l.v, l.err
}
Some dependencies are expensive to initialize (TLS-heavy clients, large config loads, SDKs that fetch metadata). I use sync.Once to ensure initialization happens exactly once, even under concurrent access. The important detail is capturing the initialization error and returning it consistently; Once only runs the function once, even if it fails, so you need to decide whether failures should be cached or retried. For most services, caching is correct: if the dependency can’t initialize, the service should fail fast or degrade explicitly. The snippet below implements a lazy client with Client() that either returns the initialized client or the init error. This keeps call sites simple and prevents subtle races where two goroutines try to initialize the same global client simultaneously.
Related snips
package api
import (
"net/http"
"runtime/debug"
)
Expose build metadata for debugging deploys
export interface RetryOptions {
retries: number;
baseMs: number;
maxMs: number;
signal?: AbortSignal;
onRetry?: (attempt: number, delay: number, err: unknown) => void;
Exponential backoff with jitter for retries
package dbutil
import (
"context"
"github.com/jackc/pgconn"
Retry Postgres serialization failures with bounded attempts
use crossbeam::channel::unbounded;
use std::thread;
fn main() {
let (tx, rx) = unbounded();
Crossbeam for advanced concurrent data structures
// Creating a Promise
const myPromise = new Promise((resolve, reject) => {
const success = true;
setTimeout(() => {
if (success) {
Promises and async/await patterns for asynchronous JavaScript
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
Channels (mpsc) for message passing between threads
Share this code
Here's the card — post it anywhere.