Word Frequency From Fields
Rank repeated words from log lines by splitting each line with strings.Fields and accumulating counts in a map keyed by the word.
Page 5 of 8
Rank repeated words from log lines by splitting each line with strings.Fields and accumulating counts in a map keyed by the word.
Cap in-flight work with a semaphore channel so a large batch never opens more connections than the upstream tolerates.
Verify that deferred calls run LIFO and that recover inside a deferred function converts a panic into a normal error return.
Ship templates and static files inside the binary with go:embed so deployment is one artifact and assets cannot drift from code.
Clone and merge maps with the maps package and compare nested structures with reflect.DeepEqual so shared-reference bugs surface immediately.
Order slices of any comparable type with the generics-based slices package — sort, sorted, and custom comparisons without interface boilerplate.
Convert strings to numbers and back with strconv, surfacing parse errors as values instead of panics so bad input fails predictably.
Inspect upcoming bytes with Peek without consuming them, then ReadString and drain the rest, the core moves for line-based protocol parsing.
Teach Scanner to split records on any delimiter by writing a SplitFunc with advance, token, and the three return cases every implementation needs.
Guard a broadcast close with sync.Once so the second call is a no-op instead of a panic, and every subscriber drains its channel cleanly.
Launch several workers that race to produce a value, then take the first arrival from a shared channel and cancel nothing because losers simply finish unused.
Extract concrete values from interface values with comma-ok assertions so a mismatched dynamic type falls into an error branch instead of a panic.
Implement container/heap.Interface on an int slice, then drive Init, Push, and Pop so values always come out in priority order without sorting.
Generate an Ed25519 key pair, sign a fixed message, and show tampering either the message or the signature flips Verify to false.
Bundle text and template directories into the binary with go:embed directives, then read them through io/fs without shipping loose files.
Unwrap error chains with errors.As to reach a concrete error type, so code can read structured fields like Path or Timeout instead of parsing messages.
Control column width, zero padding, and left alignment with printf verbs so tabular CLI output and fixed-width logs line up without manual spacing.
Fan out work to goroutines, collect each result through a buffered channel, and join the workers with a WaitGroup so the channel drains fully before printing.
Attach a cookiejar to an http.Client so Set-Cookie responses are stored and replayed automatically, keeping session handshakes out of your handlers.
Show what explicit conversions really do: int64 to int8 drops high bits, float to int truncates toward zero, and overflow wraps modulo the width.
Build a composite interface by embedding io.Reader and io.Closer plus your own method, so callers depend on capability sets instead of concrete types.
Labeled break jumps out of every nesting level and labeled continue restarts the outer loop, replacing flag-checked exits across nested range scans.
Struct values inside maps are not addressable: copy the value out, mutate, store back, or keep pointers in the map for one-step updates.
Drop every entry failing a predicate in one pass with maps.DeleteFunc instead of collecting keys and deleting them in a second loop.
Count set bits, measure leading and trailing zeros, rotate, and reverse bytes with the math/bits intrinsics instead of hand-rolled loops.
Round, RoundToEven, Floor, Ceil, and Trunc disagree most on negative halves; this table shows each function's rule side by side.
Declare a named function type, assign funcs and closures to it, compose pipelines from it, and check nil before calling a zero-value variable.
Show why a value receiver cannot mutate the caller copy and why methods needing mutation must use a pointer receiver, with a compile-level type set view.
Use os.ReadFile and os.WriteFile for whole-file IO with explicit permissions, and classify read failures with errors.Is instead of panicking.
Substitute matches with capture groups using $1 indexes and ${name} named references, including the brace form that delimits adjacent text.
Read runtime.ReadMemStats once to observe heap allocation and GC counters; values change per run, so treat them as diagnostics rather than promises.
Hash short payloads with sha256.Sum256 and render the digest as hex, or stream larger data through sha256.New with io.Copy.
Register SIGINT and SIGTERM with os/signal.Notify, stop workers through the channel, and always call signal.Stop to release the notify goroutine.
Render integers in any base, floats with fixed precision, and quoted strings with strconv.Format* and Append* helpers for allocation-free building.
Wrap arbitrary text with strings.Quote so control characters and quotes become visible Go literals, which is what you want in logs and diff output.
Check membership in strings with Contains, HasPrefix, HasSuffix, and Count so routing decisions and validations read as declarations instead of index math.
Embed a struct anonymously so its fields and methods are promoted onto the outer type, including through deeper nesting levels.
Use a tagless switch as a flat condition chain, then steer fallthrough deliberately: it enters the next case body unconditionally unless break exits.
AddDate rolls overflowing days into the next month, so January 31 plus one month lands in March; clamp with day zero to stay at month end.
Break a URL into scheme, host, path, and query with net/url.Parse, and rebuild or modify components through the returned struct instead of string surgery.
Inner := declarations shadow outer identifiers inside their own scope; learn the patterns that silently hide values and how to avoid them.
Declare variadic functions, forward their arguments with the ... spread to inner calls, and hand whole slices to them without copying.
Rely on Go zero values: declare with var and use immediately, learn where nil maps stay read-only, and give mutexes no explicit initialization.
Rows of a two-dimensional slice can share one backing array: append on one row overwrites the next row, so allocate each row independently.
Encrypt and decrypt with AES-GCM from the standard library: a random nonce travels with the ciphertext and one flipped bit fails authentication on open.
Extraction validates every entry name before touching disk: absolute paths and .. components are rejected so archives cannot write outside the target.
Assign or pass [N]T arrays and each call copies the whole value, while a slice view of the same array keeps sharing the underlying storage.
Store and swap typed snapshots with atomic.Pointer: loads need no type assertion, and CompareAndSwap matches pointer identity rather than field values.
Guard a single counter with atomic.Int64 and protect cross-field invariants like budgets with a mutex, choosing the primitive that matches the workload.
math/big computes factorials and powers that overflow int64, with Exp for exponents and IsInt64 to detect values that no longer fit in machine words.
Represent rates as big.Rat rational numbers so one-third stays exact in division, comparison, and re-float, instead of drifting through float64.
encoding/binary packs fixed-width integers in big-endian order for wire headers and shrinks small values into one-to-two-byte varints with AppendUvarint.
Encode fixed-width structs with binary.Write and binary.Read so the on-disk layout is explicit, byte counts are predictable, and endianness stays controlled.
A Scanner stops with token too long once a line exceeds 64KB; Buffer raises the cap so oversized log lines stream through without crashing.
bufio.Writer stages small writes in a buffer until Flush hands them on, and Buffered reports exactly how many bytes are still pending.
Grow a bytes.Buffer once, append strings bytes and runes through the io.Writer interface, then Reset it to reuse the backing array across batches.
Use a buffered chan struct{} as a counting semaphore: capacity caps concurrent workers, sends acquire, receives release, peak stays inside.
Decide per request whether the client follows a redirect by installing CheckRedirect, counting the chain length and stopping with http.ErrUseLastResponse.
cmp.Or returns the first non-zero argument, so environment fallback chains collapse into one line instead of nested if blocks per config key.
Register cleanup with context.AfterFunc so a canceled context triggers it in its own goroutine, and stop cancels the registration before the context ends.
WithTimeoutCause attaches a business reason to the deadline: ctx.Err stays DeadlineExceeded while context.Cause returns the specific cause for the failure.
Derive a reporting context with WithoutCancel so parent cancellation never reaches it, while context.Cause still explains why the parent stopped.
hash/crc32 computes an IEEE checksum over a payload, flags a tampered byte through a mismatching digest, and folds incremental chunks with Update.
Reader options adapt csv parsing to real files: Comma switches the delimiter, and LazyQuotes tolerates stray quotes instead of failing the row.
csv.NewWriter buffers rows behind an io.Writer, quoting commas and embedded quotes automatically, with Flush committing and Error reporting deferred failures.
Duplicate nested config before mutation with a recursive deep copy over map[string]any and []any, so edited snapshots never touch the original values.
See why defer inside a loop holds every resource until the function returns, and how extracting the iteration body closes each file on schedule.
A named result lets a deferred function rewrite the error after return: the Close failure is never lost and only wins when the body had none.
Trust magic bytes over file extensions: http.DetectContentType inspects the first 512 bytes and returns the canonical MIME type for upload validation.
Give producer and consumer functions send-only or receive-only channel parameters so misuse of a pipeline stage fails at compile time, not in production.
Signal completion with chan struct{} channels that carry zero bytes, broadcast to every waiter with close, and use map[string]struct{} as a free set.
Round-trip a typed catalog through encoding/xml: struct tags turn fields into attributes and child elements, and Unmarshal reads them back into the same values.
Errors can implement Is(error) bool so errors.Is matches by domain rules like status codes instead of requiring identical messages or pointers.
Wrap the stdlib ErrUnsupported sentinel in your own error so callers detect missing capabilities with errors.Is, not ad-hoc per-backend message strings.
Normalize user-supplied paths with filepath.Clean and Join, compute Rel between trees (a ../../-prefixed path, not an error), and split Base and Dir.
Match file names against shell-style patterns with filepath.Glob and fs.Glob, getting sorted results and an empty slice rather than an error on no match.
Walk a directory tree with filepath.WalkDir, tally files by extension, and return fs.SkipDir on dot-prefixed directories to prune hidden subtrees.
Implement flag.Value with Set validating each occurrence and String rendering the result, so a single -tag can repeat and accumulate into one slice.
Bind flags and positional arguments to an isolated flag.FlagSet: Parse splits flags from trailing operands and Args, NArg, and Arg expose the rest.
Sqrt of negatives yields NaN that fails every comparison, overflow yields Inf; IsNaN and IsInf guards keep NaN out of aggregated sums before it spreads.
Grow a reusable byte buffer with fmt.Appendf instead of fmt.Sprintf, so each formatted segment joins one backing array instead of allocating a new string.
Split read failures into expected and unexpected branches: fall back to defaults on fs.ErrNotExist and let other wrapped errors bubble up for the caller.
Feed code an in-memory fstest.MapFS so file-reading logic is tested against fixed content, with no temp directories or disk fixtures to clean up.
Variadic Option closures applied over defaults make client constructors extensible: callers override only the knobs they care about.
Write Map and Filter once with generics, reuse them for any element type, and chain filter before map while types infer at the call site.
encoding/gob serializes structs with maps and slices into a byte stream and restores them into fresh values with deep-copied composite fields.
A panic in a goroutine kills the whole process unless that same goroutine recovers; workers report failures through a channel instead of crashing main.
gzip.Writer wraps a byte buffer and Close flushes the final block; gzip.Reader hands the stream back through io.Copy so the round trip restores bytes exactly.
Race two replica calls through select and keep the first response, then cancel the derived context so the losing goroutine exits instead of leaking.
Encode bytes to lowercase hex with hex.EncodeToString, decode back losslessly, and see odd-length or invalid input fail with explicit errors.
http.Header canonicalizes keys on Set and matches them case-insensitively on Get, while Add stacks multiple values under one header name.
Attach httptrace hooks to a request against an httptest loopback server so connection reuse and first-byte arrival are observable without any external network.
Back an insertion-ordered map with a slice of entries plus an index map so set, get and delete stay O(1) while listing order matches insertion.
Chain readers sequentially with io.MultiReader and cap total consumption with io.LimitReader so combined streams stop cleanly at a byte budget.
io.Pipe hands bytes between goroutines synchronously: each Write blocks until the reader takes it, and the writer must Close to end the stream.
Frame parsing needs exact lengths: io.ReadFull reads until the buffer is full and reports ErrUnexpectedEOF on short payloads instead of silent truncation.
Read arbitrary records from a fixed-width stream with io.Seeker: absolute, relative, and end-relative seeks land exactly on record boundaries.
io.TeeReader mirrors every byte read into a hash.Hash, so one io.Copy pass forwards the payload and produces its digest without buffering it twice.
A const block with 1 << iota produces non-overlapping bit flags, and a has method checks permission masks with bitwise AND instead of booleans.
iter.Pull converts a push-style Seq into next and stop functions, so two generators can be advanced in lockstep inside one plain loop.