JSON Marshal Rejects NaN And Inf
json.Marshal fails with an unsupported value error for NaN and Inf floats, so sensor-style readings must be filtered or sanitized before encoding.
Page 6 of 50
json.Marshal fails with an unsupported value error for NaN and Inf floats, so sensor-style readings must be filtered or sanitized before encoding.
encoding/json silently drops unexported struct fields, and the json:"-" tag excludes exported ones from both marshal and unmarshal roundtrips.
Decode custom string fields through UnmarshalText so one method owns trimming, parsing, and rejecting invalid duration syntax.
Sweep a slice once with Kadane: reset the running sum when it turns negative, track the best window, and print both the sum and the winning subarray.
Walk the first word column by column and compare against every other word, returning the longest common prefix as soon as any column diverges or ends.
Load numbers into a set and only count runs at their start (x-1 missing), so each element is visited at most twice and stays O(n).
The Luhn checksum doubles every second digit from the right, folds two-digit products, and accepts the number only when the total divides by ten.
make(map[K]V, n) preallocates room for n entries so bulk inserts skip repeated rehash growth, and maps.Copy into a sized map gets the same hint.
append returns a new slice header, so map values must be written back; a dropped append never shows up in the map regardless of spare capacity.
Build a fresh map from a filtered iter.Seq2 with maps.Collect while the source map stays untouched throughout the rebuild.
Walk the old map for removals and value changes, the new map for additions, then sort the key slices so diff reports stay reproducible.
Copysign takes the magnitude of one float and the sign bit of another, while Signbit reports the sign directly, so -0.0 is detectable as signed.
Rebuild a matrix with rows and columns exchanged through nested loops over a fresh [][]int, keeping the source untouched for shape-aware transformations.
Keep one head element per slice in a min-heap and always pop the smallest, so k sorted slices merge in one pass without re-scanning.
A second stack records each new minimum as it is pushed and pops it back off with the main stack, keeping the current minimum one read away.
Compact non-zero values to the front with two indexes that swap in place, pushing every zero to the back while preserving the relative order of values.
SplitHostPort separates host and port with required brackets for IPv6 literals, and JoinHostPort adds them back when joining either address family.
new(T) allocates a zeroed value and returns a pointer to any type, while make builds ready-to-use slices, maps, and channels only.
sync.OnceFunc replays the same panic value on every call after setup fails, unlike Once.Do where a panicking init is skipped as done.
Wrap a producer channel with orDone so a downstream consumer can cancel mid-stream while the wrapper and the producer both exit instead of leaking.
os.Pipe creates a kernel-level pipe of *os.File descriptors: a writer goroutine closes the write end so the Scanner reader reaches EOF cleanly.
Guard integer addition and multiplication against wraparound with range checks and divide-back verification so bad inputs fail loudly.
Multiple init functions in one file execute top to bottom after imports load, so config setup and connection warming finish before main starts.
Check palindromes by converging two indexes over a rune slice, so multibyte text like CJK phrases is compared per character instead of per byte.
Give each map key its own sync.Once guarded by one mutex, so expensive per-key setup runs exactly once even when many goroutines race the same key.
& takes an address, * reads or writes through it, and a nil pointer must be checked before dereferencing or the program panics at runtime.
Precompute a prefix slice so any sub-range sum becomes two index lookups, turning repeated O(n) scans into constant-time queries.
A custom io.Reader wraps another reader and rewrites each filled buffer in place, passing byte counts and EOF straight through so ReadAll composes.
Redact and mask each match through a ReplaceAllStringFunc callback, since replacement templates cannot run per-match logic like length-based masking.
Run-length encoding appends each run's count after its byte, and decoding rebuilds the original text only when every count was written back.
Stop a single worker with runtime.Goexit: deferred calls still run, siblings keep going, and the group reports which workers finished versus bailed out.
Yield the processor between appends with runtime.Gosched under GOMAXPROCS(1), so two goroutines visibly alternate and the recorded order proves each handoff.
Wrap any handler with middleware that injects nosniff, frame-deny, referrer and CSP headers so every response ships the same baseline defenses.
Both sides stay ready throughout the loop, so select picks a case by uniform pseudo-random choice and the win counts vary across runs.
Receiving from a closed channel stays safe and drains buffered values before zero-and-false, while a send panics until recover catches it.
A reserved sentinel job value makes a worker exit early, and closing the jobs channel stops the remaining workers waiting on receive.
Cancel out duplicate values with a single xor accumulator: identical pairs annihilate, leaving the one number that appears exactly once in the slice.
Extend an existing slice from an iter.Seq with slices.AppendSeq, appending into the same backing storage instead of allocating.
Watch slices.Delete shift elements left and zero the stale tail since Go 1.22, so old references into the backing array cannot leak data.
Compare slices for equality with slices.Equal and swap in a per-pair predicate via EqualFunc for case-insensitive matches.
Rotate slice elements left in place with slices.Rotate: no new backing array, wraparound at the end, and composable repeated shifts.
Convert slices to iter.Seq with slices.Values and rebuild with slices.Collect, so consumers can accept any iterator without caring about storage.
Track window maximums with a monotonic deque of indexes whose values stay decreasing, so each position pops outdated candidates and reads the front.
http.StatusText turns numeric status codes into canonical reason phrases and returns an empty string for unregistered codes like 599.
Append numbers into one reusable byte buffer with strconv.AppendInt and AppendQuote, truncating with buf[:0] between rounds instead of allocating new strings.
Reversing bytes scrambles multi-byte runes into invalid UTF-8, so reversal has to walk []rune pairs from both ends to keep text intact.
Compare auth scheme names with strings.EqualFold so Bearer, BEARER and bearer all route correctly; credentials themselves need a constant-time compare.
Marshal a struct and unmarshal it into map[string]any to add or delete keys dynamically, then remarshal with keys in sorted order.
Pipe data through a subprocess with StdinPipe and StdoutPipe: write lines to the child, stream its sorted output back with a Scanner, then Wait for exit.
A supervisor loop respawns a worker goroutine after each recovered panic, stops once the worker completes, and gives up after a fixed attempt budget.
A panic inside sync.Once.Do still marks the Once done, so later calls skip the init and a failed initialization is never retried.
Load text templates through template.ParseFS from any fs.FS source, so tests can use fstest.MapFS while production swaps in embed.FS untouched.
Example functions run under go test with their // Output: comment compared verbatim, keeping documentation snippets honest as the code evolves.
t.Parallel marks subtests to pause and run concurrently after serial setup, while copying each case into the closure keeps shared loop state per-test.
Show that time.Duration(1500) means 1500 nanoseconds, not milliseconds: untyped integer conversions silently shrink durations by three orders of magnitude.
Compare times with Equal and Compare: the eq operator fails across locations and after Round strips the monotonic clock reading.
Try a prioritized list of layouts with time.Parse and wrap the last error, so timestamps arriving from different systems parse with one entry point.
Walk two pointers inward tracking the tallest wall on each side; water above a column is bounded by the shorter of the two maxima.
Two indices walking inward from both ends of a sorted slice locate a pair summing to the target in one pass, discarding one impossible element per step.
Build a FIFO queue from two stacks so each element moves at most twice: push appends to the inbox stack, pop reverses it once into the outbox stack.
Convert between string and []byte without copying via unsafe.String and unsafe.StringData, and state the read-only contract that keeps it safe.
Parse query strings with url.ParseQuery and surface malformed input: bare semicolons and invalid percent escapes return errors instead of dirty data.
Run sequential batches of goroutines with one WaitGroup: after each Wait the counter is back at zero, so the same group serves the next phase.
Each WaitGroup worker writes its result into a fixed slot, and errors.Join merges the non-nil errors into one value after all goroutines finish.
Greedy wrapping breaks text into lines no wider than the limit, splitting only at spaces and pushing an overlong word to its own line.
Generate an ECDSA key, issue a self-signed certificate with CreateCertificate, parse the DER back with ParseCertificate, and encode it as PEM.
Stream XML incrementally with xml.Decoder.Token: start elements, character data, and end elements arrive as you ask, without loading the whole tree.
Emit ANSI SGR escape sequences to color terminal output, then strip every sequence with a regex so piped or CI output stays clean.
Extend AbstractQueuedSynchronizer with tryAcquireShared and tryReleaseShared to rebuild a countdown latch from the shared queue primitives.
Assign a String[] to an Object[] alias and store an Integer to trigger ArrayStoreException at runtime while the original array stays intact.
Primitive arrays sort ascending only; reversing or field-based ordering means boxing to Integer[] and passing a Comparator to Arrays.sort.
Run one echo roundtrip over AsynchronousSocketChannel completion handlers while the main thread parks on a CountDownLatch until callbacks land.
Capture produced bytes in a ByteArrayOutputStream, replay them through a ByteArrayInputStream, and reuse the same buffer after reset without reallocating.
Character.digit maps a char to its value under a radix and forDigit goes back; invalid digits return -1 instead of throwing.
Character.getName reports the official Unicode name of any code point, or null for unassigned ones, ideal for debugging odd glyphs.
Fill a CharBuffer with put, flip to drain with get, and compact to keep unread chars for the next write instead of clearing them away.
Charset.forName accepts case-insensitive aliases while each charset keeps one canonical name; availableCharsets lists every registered charset.
Wrap a failing dependency in a breaker: consecutive failures trip it to OPEN and later calls fast-fail instead of hammering a dead upstream.
Prefer a copy constructor over clone(): a shallow clone shares mutable list state, while an explicit constructor copies fields deliberately.
Build each CollationKey once and sort by keys, then compare repeatedly without paying Collator.compare on every lookup during large sorts.
Return null from a ConcurrentHashMap remapping function to remove the entry, keep absent keys absent, and replace existing values in place.
addFirst and pollLast drain a ConcurrentLinkedDeque from opposite ends without coordination; size() walks the chain and iterators stay weakly consistent.
System.console() may be null when the program runs without a terminal; guard it, prompt with readLine, and take secrets as char arrays from readPassword.
Split an array into forked leaves, fold child results in onCompletion, and read the grand total back through getRawResult after invoke.
CRC32C update() calls accumulate the same checksum whether input arrives whole or chunked, and flipping one byte changes the value, exposing corruption.
Encode one CSV field per RFC 4180: quote when the value holds a comma, quote, or line break, and double embedded quotes when escaping.
user.dir anchors relative paths for the whole JVM: Paths.get("").toAbsolutePath() lands on the same directory that System.getProperty("user.dir") reports.
Check whether two inclusive date ranges overlap with a two-comparison rule covering containment, adjacency, and disjoint spans.
parseBest tries queries from most to least complete: an optional-section formatter parses timestamps, datetimes, and date-only strings without try/catch chains.
Pattern letter B formats the finer day period — morning, afternoon, evening, night — where am/pm collapses the whole day into two halves.
NaN compares false against everything including itself: use Double.isNaN for detection and Double.compare for ordering, which treats NaN as equal to itself.
doubleToLongBits exposes the IEEE 754 layout: plus and minus zero differ only in the sign bit, every NaN canonicalizes, and the raw form keeps payloads.
Count terminal columns where CJK and fullwidth characters occupy two cells, so padded tables align where String length() undercounts wide text.
Sign a payload with the Ed25519 JCA Signature API and verify both the original bytes and a tampered copy, which must fail.
Validate user emails with a conservative regex pattern that accepts common shapes and rejects spaces or missing domains.
exceptionallyCompose swaps a failed future for a fallback future instead of a plain value, so recovery can itself be an async call.
Stop a pool politely: shutdown stops intake, awaitTermination grants a grace period, shutdownNow interrupts stragglers, then one more wait confirms.
An uncaught execute() task kills only the worker and the pool spawns a replacement, while submit() traps the exception inside its Future.
Create a symlink and read back the raw target stored inside it with Files.readSymbolicLink, keeping toRealPath as the follow-the-link view of the same path.
Stream the whole directory tree with Files.walk, sort by byte size, and keep only the top entries for disk usage triage.