Skip to content

Archive

Standard Library

147 articles
Go 11 Sep 2026 4 min read

Remove Adjacent Duplicates from Go Slices with slices.Compact

Duplicate values often arrive in runs: repeated status events, sorted IDs, or adjacent tokens produced by a parser. When only consecutive duplicates need to disappear, slices.Compact handles the operation without a handwritten loop. The distinction is specific. slices.Compact collapses adjacent equal values; it doesn’t search the entire slice for duplicates. It also modifies the slice’s backing storage, so callers need to account for aliasing. Remove adjacent duplicates with slices.Compact Pass a slice whose element type is comparable and assign the returned slice:

Go 11 Sep 2026 6 min read

Remove a Range from Go Slices with slices.Delete

Removing a known range from a Go slice is easy to express with slices.Delete. Give it the slice and a half-open index range, and it closes the gap for you. The small details matter. slices.Delete changes the slice’s contents, returns a slice with a new length, and panics for an invalid range. Using it well means treating those behaviors as part of the operation rather than as implementation trivia. Remove a range with slices.Delete Suppose a pipeline contains stages that are no longer needed:

Go 11 Sep 2026 5 min read

Preserve Equal Element Order in Go with slices.SortStableFunc

Sometimes sorting by one field is only half the requirement. You may want jobs grouped by priority while keeping their arrival order inside each priority, or records grouped by category without disturbing an earlier ranking. slices.SortStableFunc is built for that case. It sorts a slice in place using a custom comparator, but elements that compare equal keep their original relative order. Preserve equal elements with slices.SortStableFunc Suppose jobs arrive in this order:

Go 11 Sep 2026 5 min read

Iterate Go Map Values with maps.Values

Sometimes a Go map’s keys are irrelevant to the next operation. You may need to total counters, inspect status values, or pass the values into an iterator-aware helper. A plain map range works well inside one loop, but it doesn’t give you a value sequence that can cross an API boundary. Since Go 1.23, maps.Values returns an iter.Seq over a map’s values. That lets code consume values directly and postpone slice allocation until a later operation actually needs a slice.

Go 11 Sep 2026 4 min read

Iterate Go Map Pairs with maps.All

A normal range loop is often the clearest way to walk through a Go map. The situation changes when another API expects an iterator rather than a map. Starting in Go 1.23, maps.All provides that bridge by exposing a map’s key-value pairs as an iter.Seq2. maps.All doesn’t copy the map into a slice or build a second map. It returns an iterator that can feed a range loop or another iterator-aware function. The main constraint is familiar from map iteration: pair order is unspecified.

Go 11 Sep 2026 5 min read

Iterate Go Map Keys with maps.Keys

Sometimes you need only the keys from a Go map. A plain range loop handles that case well, but an iterator becomes useful when the keys need to flow into another iterator-aware API or when a function should expose keys without first allocating a slice. Since Go 1.23, maps.Keys returns an iter.Seq over a map’s keys. You can range over it directly, stop early, or pass it to helpers such as slices.Sorted and slices.Collect.

Go 11 Sep 2026 5 min read

Insert Values into Go Slices with slices.Insert

Adding a value to the middle of a Go slice takes more work than appending at the end. Elements after the insertion point need to move, and the operation may require a larger backing array. slices.Insert packages that splice into one standard-library call. The function accepts a slice, an index, and one or more values. It returns the resulting slice, so the usual form assigns that result back to the slice variable.

Go 11 Sep 2026 5 min read

Find the Smallest Go Slice Value with slices.Min

Finding the smallest value in a Go slice doesn’t require sorting or a hand-written comparison loop. When the element type has a natural order, slices.Min states the operation directly and leaves the input untouched. The call is compact, but its contract matters at the edges. An empty slice causes a panic, and a floating-point NaN propagates to the result. Those cases are best handled where the application can attach useful meaning to them.

Go 11 Sep 2026 5 min read

Find the Largest Go Slice Value with slices.Max

Finding the largest value in a slice is a small operation, but handwritten loops still create room for awkward initialization and missed empty-input handling. For ordered values such as integers, strings, and floating-point numbers, slices.Max expresses the operation directly. The function scans the slice and returns its maximal element. It doesn’t sort or modify the input. Two details deserve attention in production code: an empty slice causes a panic, and floating-point input containing a NaN produces a NaN result.

Go 11 Sep 2026 5 min read

Find Minimum Struct Values in Go with slices.MinFunc

Finding the smallest number in a slice is straightforward, but real programs often need the cheapest quote, earliest task, shortest route, or lowest-priority struct. Those values aren’t ordered by Go itself, so slices.Min can’t express the rule. slices.MinFunc handles that case. You provide the slice and a comparator; it returns the element that is minimal according to that comparator. What slices.MinFunc does The function accepts slices of any element type:

Go 11 Sep 2026 5 min read

Find Maximum Struct Values in Go with slices.MaxFunc

Finding the largest integer in a Go slice is easy. The problem gets more interesting when the slice contains structs and “largest” means the build with the longest duration, the newest release, or the highest application-specific score. slices.MaxFunc is designed for that case. It scans a slice and returns the maximal element according to a comparator you provide, so the ordering rule can live next to the selection instead of being hidden in a separate sort.

Go 11 Sep 2026 6 min read

Find Exact Values in Go Slices with slices.Index

A slice often holds a short sequence where you need the position of one exact value: a status in a workflow, a command-line argument, a feature name, or an ID in a small ordered list. slices.Index handles that case directly. It returns the first matching index, or -1 when the value isn’t present. That return contract is simple, but it affects how callers should use the result. Indexing the slice before checking for -1 will panic, repeated searches still scan linearly, and exact equality isn’t suitable for every data type or matching rule.

Go 11 Sep 2026 4 min read

Copy Go Slices with slices.Clone

A slice assignment copies the slice header, not its backing array. That detail becomes visible as soon as one variable changes an element and another variable unexpectedly sees the same change. slices.Clone gives the copied slice separate element storage with a single call. The copy is shallow. That makes it a clean fit for slices of numbers, strings, and value-only structs, but nested maps, slices, pointers, and other reference-like values still need deliberate handling.

Go 11 Sep 2026 4 min read

Copy Entries Between Go Maps with maps.Copy

Sometimes you already have a destination map and need to add another map’s entries without writing a loop. Go’s maps.Copy does exactly that: it copies every key-value pair from a source map into an existing destination map. The operation is deliberately simple. Existing destination entries remain when their keys aren’t present in the source. When both maps contain the same key, the source value replaces the destination value. That makes maps.Copy useful for applying defaults, overrides, accumulated state, and other map-to-map merges where replacement is the intended conflict rule.

Go 11 Sep 2026 6 min read

Compare Struct Slices in Go with slices.CompareFunc

Two slices can represent ordered records rather than plain strings or numbers. Maybe they’re deployment steps, semantic-version parts, or structs sorted by a domain-specific key. When you need to answer which sequence comes first, slices.Compare isn’t enough if the elements don’t have Go’s built-in ordering. slices.CompareFunc handles that case. It compares two slices from left to right and lets you define what it means for one pair of elements to be less than, equal to, or greater than the other.

Go 11 Sep 2026 5 min read

Compare Go Slices for Equality with slices.Equal

Two slices can contain the same number of elements and still represent different sequences. When equality means “same length, same value at every index,” slices.Equal expresses that check directly without a manual loop. The function is small, but a few details matter in production code. Element order counts, nil and empty slices compare equal, element types must be comparable, and floating-point NaN values don’t compare equal to themselves. Compare Go slices with slices.Equal For strings, integers, booleans, and other comparable element types, pass both slices directly:

Go 11 Sep 2026 6 min read

Compare Go Maps with Custom Value Rules Using maps.EqualFunc

Two maps can represent the same application state even when their values aren’t directly comparable with ==. One map might hold structs containing slices, another might use a different value type, or a text field might be considered equal regardless of letter case. maps.EqualFunc handles that situation by keeping key comparison fixed while letting you define value equality. It is a compact option when the question is strictly whether two maps contain the same keys and equivalent values.

Go 11 Sep 2026 5 min read

Check Exact Values in Go Slices with slices.Contains

Code often needs a simple membership check: is this status allowed, does this short list contain a requested format, or has this identifier already appeared in a small batch? slices.Contains answers that question directly for comparable values and returns a boolean. The operation is deliberately narrow. It checks exact equality, doesn’t return a position, and scans the slice until it finds a match or reaches the end. Those details make it a good fit for some lookups and a poor fit for others.

Go 11 Sep 2026 6 min read

Check Custom Slice Ordering in Go with slices.IsSortedFunc

Sometimes you need to know whether a slice is already in the right order, not sort it again. That comes up when validating API input, checking an invariant before binary search, or avoiding unnecessary work when records are expected to arrive ordered. For plain numbers and strings, slices.IsSorted handles the common case. When the elements are structs or the ordering is application-specific, slices.IsSortedFunc lets you define exactly what “sorted” means and returns a boolean without rearranging the slice.

Go 10 Sep 2026 7 min read

Test Concurrent Go Code with testing/synctest

Tests for concurrent Go code often become timing tests by accident. A goroutine starts, the test sleeps for 20 milliseconds, then checks whether something happened. That can pass thousands of times and still fail on a loaded CI runner because the sleep never proved the goroutine reached the state you cared about. Go’s testing/synctest package gives these tests a better model. It runs code inside an isolated bubble where time is virtualized, and synctest.Wait can synchronize the test with goroutines in that bubble. The result is especially useful for code built around timers, context deadlines, retries, and background goroutines.

Go 10 Sep 2026 5 min read

Sort Go Iterator Values with slices.Sorted

An iter.Seq is convenient while values are flowing through a pipeline. Sorting changes the problem: a sort needs all of those values available at once. If the next step needs an ordered slice, Go has a standard-library helper that makes that boundary explicit. Go 1.23 added slices.Sorted. It consumes an iter.Seq of ordered values, collects the values into a new slice, sorts that slice in ascending order, and returns it.

Go 10 Sep 2026 7 min read

Set Per-Response Write Deadlines in Go with http.ResponseController

A server-wide WriteTimeout is a useful safety net, but some handlers have different timing needs. A small JSON response and a streaming export shouldn’t necessarily share the same write budget. When the deadline belongs to one response rather than the whole server, Go’s http.ResponseController gives the handler a direct way to set it. http.ResponseController.SetWriteDeadline applies a write deadline to the current response. It also solves a practical middleware problem: instead of asserting a concrete optional interface at every call site, a handler can ask the controller to find the capability through compatible ResponseWriter wrappers.

Go 10 Sep 2026 6 min read

Search Go Struct Slices with slices.BinarySearchFunc

A slice of structs can be sorted by an ID, timestamp, or other field even though the struct itself has no built-in ordering. When you need repeated lookups in that sorted data, slices.BinarySearchFunc lets the search use the same ordering without building a separate index. The comparator is the part that deserves attention. It doesn’t compare two slice elements. It compares one element from the slice with the search target, and its ordering must agree with the way the slice is sorted.

Go 10 Sep 2026 5 min read

Restrict Slice Capacity in Go with slices.Clip

A Go slice can be much smaller than the backing array it refers to. That spare capacity is useful when more append calls are coming, but sometimes you deliberately want the opposite: a result whose capacity stops exactly at its current length. slices.Clip expresses that operation directly. It reduces a slice’s capacity to its length without changing its elements or length. The detail that matters is what this does, and doesn’t, imply about memory.