Clear Builtin Resets Slices And Maps
Reset a slice in place with the clear builtin, which zeroes elements while keeping length, and empty a map completely, replacing the manual zeroing loops.
Page 7 of 8
Reset a slice in place with the clear builtin, which zeroes elements while keeping length, and empty a map completely, replacing the manual zeroing loops.
Implement the fmt Stringer interface so Println, Printf %v, and logging render a type in one controlled form instead of raw struct braces.
Consume iter.Seq iterators with range: maps.Keys streams keys on demand, slices.Sorted materializes them ordered, and custom yield functions stop on break.
SetEscapeHTML on a json.Encoder decides whether <, >, and & ship as unicode escapes, the default that keeps JSON safe to embed in HTML pages.
Embed structs inside JSON payloads: anonymous fields without a tag flatten into the outer object, while an embedded type with a json tag stays a nested object.
Decode JSON numbers as json.Number with UseNumber so integers beyond float64's 2^53 keep every digit instead of silently losing precision.
Seed math/rand/v2 with NewPCG for reproducible rolls and shuffles, and fall back to auto-seeded package functions when determinism is not required.
Probe a busy mutex with TryLock for a non-blocking fast path, skip the critical section while it is held, and block only when entering it is required.
Inspect values with Printf verbs: %v and %+v for fields, %#v for Go syntax, %T for the dynamic type, %q for quoted strings, and width-precision for tables.
Route HTTP methods and path segments with Go 1.22 ServeMux: method-scoped patterns, {id} wildcards through PathValue, and automatic 404/405 for misses.
Search a sorted slice with slices.BinarySearch, which returns both the match position and a found flag, then insert at that position to keep the order.
Cut strings at the first separator and peel prefixes or suffixes with CutPrefix and CutSuffix, using the returned boolean instead of hand-rolled index checks.
Rewrite many substrings in one pass with strings.NewReplacer: pairs compete by argument order, matches never overlap, and the replacer is reusable.
Guard a shared cache with sync.Map: LoadOrStore inserts atomically when absent, Load reads with comma-ok, and Range walks entries without blocking writers.
Compute an expensive configuration value once with sync.OnceValue so concurrent callers share one result, and gate one-shot warnings with sync.OnceFunc.
Drive periodic maintenance with time.NewTicker, consume ticks in a select loop alongside a stop channel, and always Stop the ticker so timers do not leak.
WaitGroup Go starts each goroutine with Add and Done already handled, so fan-out code becomes a single closure call before one Wait joins everything.
Trace defer's LIFO order around a panic, then recover in a deferred closure so the program keeps running instead of crashing.
Defer payload decoding with json.RawMessage: keep raw bytes in the envelope struct, then decode into the right target type once the kind is known.
Reject JSON payloads with unexpected keys by enabling DisallowUnknownFields, so typos and stale clients surface as decode errors instead of zero values.
Map Go struct fields to JSON keys with tags, drop empty fields via omitempty, and hide internals with the dash tag during round trips.
Probe map keys with the comma-ok idiom, then lean on maps.Clone, maps.Equal, and maps.DeleteFunc for copying, comparing, and pruning.
Use select with a default branch for non-blocking channel sends and receives, and a time.After branch to bound how long a receive waits.
Use the slices package for Contains, Sort, Compact, Equal, Max, and DeleteFunc so common slice chores stop being hand-written loops.
Order structs by several keys with slices.SortFunc and cmp.Compare, flipping the comparison to get descending secondary sorts.
Parse config strings with strconv using Atoi, ParseFloat, ParseBool, and ParseUint, inspecting NumError fields and falling back to defaults.
Cut lines apart with strings.Fields and Split, reassemble with Join, and finish with ReplaceAll, HasPrefix, and ToUpper.
Coordinate goroutines with sync.Cond: waiters park in a loop until a producer changes the guarded condition and calls Signal.
Share a map across goroutines with sync.RWMutex: writers take the exclusive Lock while readers only take RLock and stay concurrent.
Bound blocking work with a context deadline, propagate cancellation through nested calls, and free resources on the deferred cleanup path.
Fan out work across goroutines with errgroup and SetLimit so failures propagate on first error while concurrency stays bounded.
Wrap errors with %w and inspect chains with errors.Is and errors.As so sentinel checks survive across package boundaries.
Control the wire format of time and enum fields with MarshalJSON and UnmarshalJSON so the API contract stays stable across refactorings.
Iterate maps through sorted key slices because Go randomizes map order, so reports and golden-file tests need explicit ordering.
Control slice backing arrays with append, len, cap, and copy so shared-underlying-array bugs are avoided instead of debugged.
Assemble large strings with strings.Builder instead of += concatenation, so growth is amortized instead of quadratic buffer copies.
Consume untyped values safely with a type switch, giving each concrete type its own branch while rejecting unexpected shapes loudly.
Initialize expensive resources exactly once with sync.Once, keeping first-call latency on the caller and all later calls lock-free after the gate.
Format timestamps with reference layouts and turn durations into human units, keeping all rendering deterministic across time zones.
Run a fixed worker pool over a job channel, stop accepting work on signal, and drain in-flight jobs before returning with a WaitGroup.
Find the leftmost position where a sorted slice can accept a target using a Go binary search lower bound variant.
Generate a Gray code sequence of n bits in Go using bit manipulation where consecutive values differ by one bit.
Implement a Go bloom filter with k hash functions for probabilistic membership testing.
Implement a Go binary search tree supporting insert and delete using in-order successor for two-child nodes.
Compute single source shortest paths in a weighted Go graph using Dijkstra with container heap.
Compute the Levenshtein edit distance between two Go strings with insert, delete, and substitute operations.
Find the shortest path in an unweighted Go graph using BFS with a predecessor map for path reconstruction.
Perform topological sort on a Go DAG using DFS with cycle detection via tri-color marking.
Sort a Go slice by building a max heap in place then repeatedly extracting the maximum to the end.
Match a pattern in Go text using KMP with a precomputed failure function for linear time matching.
Solve the 0-1 knapsack problem in Go using dynamic programming with a rolling array for space optimization.
Compute the longest common subsequence of two Go strings using dynamic programming with table reconstruction.
Count inversions in a slice using a modified Go mergesort that counts crossings during the merge step.
Generate all primes up to n in Go using a segmented sieve of Eratosthenes for memory efficiency.
Sort a slice in place using Go quicksort with median-of-three pivot selection to avoid worst-case behavior.
Find all occurrences of a pattern in Go text using Rabin Karp with a rolling hash for O(n+m) average time.
Build a Go trie from a word list supporting prefix search and autocomplete suggestions ranked by frequency.
Implement a Go disjoint set union find with path compression and union by rank for near constant amortized time.
Reload configuration atomically using atomic.Value for zero-downtime config updates.
Encode a file to base64 in chunks for memory-efficient binary data transport.
Use bounded channels for backpressure in Go pipelines between producer and consumer.
Check if an IP address is within allowed CIDR ranges for network access control.
Implement a circuit breaker with state transitions and metrics for Go service protection.
Build a CLI with Cobra supporting flags subcommands and config precedence.
Set timeouts on HTTP client requests using context for preventing hanging connections.
Load config from environment variables with defaults and validation in Go.
Fan out parallel API calls with errgroup and limit concurrency in Go services.
Run parallel HTTP fetches with errgroup for concurrent fanout with first-error cancellation.
Use file locks for cross-process critical sections with flock in Go applications safely.
Use Go generics with type constraints for type-safe min and max functions.
Run tasks in a bounded goroutine pool with a job channel for controlled concurrency.
Log HTTP requests with a middleware including method path status and duration.
Implement a token bucket rate limiter as HTTP middleware for Go API throttling.
Retry operations with exponential backoff and jitter in Go for transient error handling.
Use weighted semaphore for concurrency limiting with different resource weights.
Compute an HMAC-SHA256 tag and compare it in constant time to avoid leaking the secret through timing.
Propagate cancellation and deadlines through a call tree using Go context, so abandoned work stops promptly.
Bound concurrent work by cost using a weighted semaphore, admitting tasks only while capacity remains.
Process a stream of jobs with a fixed number of goroutines, bounded channels and graceful completion.
Track hot counters with atomic operations instead of mutexes, exporting per-second rates and cumulative values for monitoring.
Parse newline-delimited JSON streams with bufio.Scanner, sizing buffers for long lines and isolating malformed records.
Log every request with chi middleware: request ids, durations, status codes, and route patterns instead of raw paths.
Trip a circuit breaker after consecutive failures, short-circuiting calls during an open period and probing recovery with a half-open state.
Resolve CLI configuration with explicit precedence from flags over environment over config file, with typed defaults and validation.
Derive a context with a deadline so downstream work is cancelled when the caller gives up, and propagate the reason through context errors.
Give outbound HTTP calls hard deadlines with context timeouts, propagating cancellation into DNS, connect, and body read phases.
Query and control Docker containers with the Go SDK, filtering by labels, streaming events, and reporting runtime stats.
Read configuration from environment variables with typed parsing and defaults, validating required fields at startup rather than at first use.
Run parallel HTTP fetches under one errgroup context so the first error cancels siblings and always reclaims goroutines.
Fan out calls to many shards with errgroup SetLimit bounding concurrency, merging partial results even when some shards fail.
Fetch several resources concurrently with errgroup so the first error cancels the rest and the combined call fails fast.
Throttle Fiber routes with a sliding-window rate limiter middleware, keying by API key with burst tolerance and custom 429 bodies.
Write generic min and max helpers constrained to ordered types, avoiding duplication across numeric and string collections.
Extract and verify JWT claims in Gin middleware, checking issuer and role before handlers, with claims injected into context.
Build a Go CI pipeline with matrix versions, module caching, lint gates, race-enabled tests, and release artifact uploads.
Batch independent Redis commands into pipelines and transactions, measuring round-trip savings and verifying atomic MULTI execution.
Configure the go-redis universal client for single, sentinel, and cluster topologies, with pool sizing and timeout discipline.
Run a hub that registers WebSocket clients into rooms, broadcasts messages to a room, and unregisters on disconnect or expiry.
Paginate PostgreSQL result sets with GORM using keyset conditions on indexed sort columns, stable under concurrent inserts.
Implement Relay-style cursor pagination with gqlgen resolvers, resolving edges and pageInfo from a keyset-ordered store.